Improve Comments in code.
[clamp.git] / src / main / java / org / onap / clamp / clds / util / CryptoUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23
24 package org.onap.clamp.clds.util;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.google.common.base.Charsets;
29
30 import java.io.IOException;
31 import java.io.UnsupportedEncodingException;
32 import java.security.GeneralSecurityException;
33 import java.security.SecureRandom;
34 import java.util.Properties;
35
36 import javax.crypto.Cipher;
37 import javax.crypto.spec.IvParameterSpec;
38 import javax.crypto.spec.SecretKeySpec;
39
40 import org.apache.commons.codec.DecoderException;
41 import org.apache.commons.codec.binary.Hex;
42 import org.apache.commons.lang3.ArrayUtils;
43
44 /**
45  * CryptoUtils for encrypting/decrypting string based on a Key defined in
46  * application.properties (Spring config file).
47  */
48 public final class CryptoUtils {
49
50     /**
51      * Used to log CryptoUtils class.
52      */
53     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CryptoUtils.class);
54     // Openssl commands:
55     // Encrypt: echo -n "123456" | openssl aes-128-cbc -e -K <Private Hex key>
56     // -iv <16 Hex Bytes iv> | xxd -u -g100
57     // Final result is to put in properties file is: IV + Outcome of openssl
58     // command
59     // ************************************************************
60     // Decrypt: echo -n 'Encrypted string' | xxd -r -ps | openssl aes-128-cbc -d
61     // -K
62     // <Private Hex Key> -iv <16 Bytes IV extracted from Encrypted String>
63     /**
64      * Definition of encryption algorithm.
65      */
66     private static final String ALGORITHM = "AES";
67     /**
68      * Detailed definition of encryption algorithm.
69      */
70     private static final String ALGORITHM_DETAILS = ALGORITHM + "/CBC/PKCS5PADDING";
71     private static final int BLOCK_SIZE_IN_BITS = 128;
72     private static final int BLOCK_SIZE_IN_BYTES = BLOCK_SIZE_IN_BITS / 8;
73     /**
74      * Key to read in the key.properties file.
75      */
76     private static final String KEY_PARAM = "org.onap.clamp.encryption.aes.key";
77     private static final String PROPERTIES_FILE_NAME = "clds/key.properties";
78     /**
79      * The SecretKeySpec created from the Base 64 String key.
80      */
81     private static final SecretKeySpec SECRET_KEY_SPEC = readSecretKeySpec(PROPERTIES_FILE_NAME);
82
83     /**
84      * Private constructor to avoid creating instances of util class.
85      */
86     private CryptoUtils() {
87     }
88
89     /**
90      * Encrypt a value based on the Clamp Encryption Key.
91      * 
92      * @param value
93      *            The value to encrypt
94      * @return The encrypted string
95      * @throws GeneralSecurityException
96      *             In case of issue with the encryption
97      * @throws UnsupportedEncodingException
98      *             In case of issue with the charset conversion
99      */
100     public static String encrypt(String value) throws GeneralSecurityException, UnsupportedEncodingException {
101         Cipher cipher = Cipher.getInstance(ALGORITHM_DETAILS, "SunJCE");
102         byte[] iv = new byte[BLOCK_SIZE_IN_BYTES];
103         SecureRandom.getInstance("SHA1PRNG").nextBytes(iv);
104         IvParameterSpec ivspec = new IvParameterSpec(iv);
105         cipher.init(Cipher.ENCRYPT_MODE, SECRET_KEY_SPEC, ivspec);
106         return Hex.encodeHexString(ArrayUtils.addAll(iv, cipher.doFinal(value.getBytes(Charsets.UTF_8))));
107     }
108
109     /**
110      * Decrypt a value based on the Clamp Encryption Key.
111      * 
112      * @param message
113      *            The encrypted string that must be decrypted using the Clamp
114      *            Encryption Key
115      * @return The String decrypted
116      * @throws GeneralSecurityException
117      *             In case of issue with the encryption
118      * @throws DecoderException
119      *             In case of issue to decode the HexString
120      */
121     public static String decrypt(String message) throws GeneralSecurityException, DecoderException {
122         byte[] encryptedMessage = Hex.decodeHex(message.toCharArray());
123         Cipher cipher = Cipher.getInstance(ALGORITHM_DETAILS, "SunJCE");
124         IvParameterSpec ivspec = new IvParameterSpec(ArrayUtils.subarray(encryptedMessage, 0, BLOCK_SIZE_IN_BYTES));
125         byte[] realData = ArrayUtils.subarray(encryptedMessage, BLOCK_SIZE_IN_BYTES, encryptedMessage.length);
126         cipher.init(Cipher.DECRYPT_MODE, SECRET_KEY_SPEC, ivspec);
127         byte[] decrypted = cipher.doFinal(realData);
128         return new String(decrypted);
129     }
130
131     /**
132      * Method used to generate the SecretKeySpec from a Base64 String.
133      * 
134      * @param keyString
135      *            The key as a string in Base 64
136      * @return The SecretKeySpec created
137      * @throws DecoderException
138      *             In case of issues with the decoding of Base64
139      */
140     private static SecretKeySpec getSecretKeySpec(String keyString) throws DecoderException {
141         byte[] key = Hex.decodeHex(keyString.toCharArray());
142         return new SecretKeySpec(key, ALGORITHM);
143     }
144
145     /**
146      * Reads SecretKeySpec from file specified by propertiesFileName
147      *
148      * @param propertiesFileName
149      *            File name with properties
150      * @return SecretKeySpec secret key spec read from propertiesFileName
151      */
152     private static SecretKeySpec readSecretKeySpec(String propertiesFileName) {
153         Properties props = new Properties();
154         try {
155             props.load(ResourceFileUtil.getResourceAsStream(propertiesFileName));
156             return getSecretKeySpec(props.getProperty(KEY_PARAM));
157         } catch (IOException | DecoderException e) {
158             logger.error("Exception occurred during the key reading", e);
159             return null;
160         }
161     }
162 }