HexHelper unit tests
[appc.git] / appc-common / src / main / java / org / onap / appc / encryption / HexHelper.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.encryption;
26
27 import java.util.HashMap;
28 import java.util.Map;
29
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 /**
34  * HexHelper utility used for encryption/decryption
35  */
36 public final class HexHelper {
37
38     @SuppressWarnings({
39         "javadoc", "nls"
40     })
41     public static final String CM_PATH = "@(#) [viewpath]/[item]";
42
43     @SuppressWarnings({
44         "nls", "javadoc"
45     })
46     public static final String CM_PROJECT = "@(#) [environment] [baseline]";
47
48     @SuppressWarnings({
49         "javadoc", "nls"
50     })
51     public static final String CM_VERSION = "@(#) [version] [crtime]";
52
53     private static final char[] HEX_TABLE = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
54         'E', 'F'};
55
56     /**
57      * The logger for this class.
58      */
59     private static final Logger LOG = LoggerFactory.getLogger(HexHelper.class);
60
61     private static Map<Character, Integer> textToHex;
62
63     static {
64         textToHex = new HashMap<>();
65         textToHex.put('0', 0);
66         textToHex.put('1', 1);
67         textToHex.put('2', 2);
68         textToHex.put('3', 3);
69         textToHex.put('4', 4);
70         textToHex.put('5', 5);
71         textToHex.put('6', 6);
72         textToHex.put('7', 7);
73         textToHex.put('8', 8);
74         textToHex.put('9', 9);
75         textToHex.put('A', 10);
76         textToHex.put('B', 11);
77         textToHex.put('C', 12);
78         textToHex.put('D', 13);
79         textToHex.put('E', 14);
80         textToHex.put('F', 15);
81     }
82
83     /**
84      * Default private constructor prevents instantiation
85      */
86     private HexHelper() {
87         // no-op
88     }
89
90     /**
91      * Converts an array of bytes to the equivalent string representation using hexadecimal notation
92      *
93      * @param bytes The bytes to be converted to a hexadecimal string
94      * @return The string representation
95      */
96     public static String convertBytesToHex(byte[] bytes) throws EncryptionException{
97
98         if (bytes == null)
99             throw new EncryptionException("Given byte array is null");
100
101         StringBuilder builder = new StringBuilder(bytes.length * 2);
102         for (byte aByte : bytes) {
103             char tempChar;
104             // Get the first 4 bits (high) Do bitwise logical AND to get rid of
105             // low nibble. Shift results to right by 4 and get char
106             // representation
107             tempChar = HEX_TABLE[(aByte & 0xf0) >>> 4];
108             builder.append(tempChar);
109
110             // Get the last 4 bits (low) Do bitwise logical AND to get rid of
111             // high nibble. Get char representation
112             tempChar = HEX_TABLE[aByte & 0x0f];
113             builder.append(tempChar);
114         }
115         return builder.toString();
116     }
117
118     /**
119      * Converts a hexadecimal string representation of a binary value to an array of bytes
120      *
121      * @param hexValue The hex representation string to be converted
122      * @return The array of bytes that contains the binary value
123      */
124     @SuppressWarnings("nls")
125     public static byte[] convertHexToBytes(String hexValue) throws EncryptionException {
126
127         if (hexValue ==null)
128             throw new EncryptionException("Given hex value is null");
129
130         byte[] bytes;
131         byte high;
132         byte low;
133         char hexChar;
134
135         StringBuilder builder = new StringBuilder(hexValue.toUpperCase());
136         if (builder.length() % 2 != 0) {
137             LOG.warn("Invalid HEX value length. The length of the value has to be a multiple of 2."
138                 + " Prepending '0' value.");
139             builder.insert(0, '0');
140         }
141         int hexLength = builder.length();
142         int byteLength = hexLength / 2;
143
144         bytes = new byte[byteLength];
145         try {
146             for (int index = 0; index < hexLength; index += 2) {
147                 hexChar = builder.charAt(index);
148                 high = textToHex.get(hexChar).byteValue();
149                 high = (byte) (high << 4);
150                 hexChar = builder.charAt(index + 1);
151                 low = textToHex.get(hexChar).byteValue();
152                 high = (byte) (high | low);
153                 bytes[index / 2] = high;
154             }
155         }
156         catch (NullPointerException e){
157             LOG.error("Given string contains not hexadecimal values", e);
158             throw new EncryptionException("Given string contains not hexadecimal values");
159         }
160
161         return bytes;
162     }
163 }