1c7a687bbf1603f16a6f28277df92e196efb0f35
[music.git] / jar / src / main / java / org / onap / music / main / CipherUtil.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  * ===================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  * 
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  * 
19  * ============LICENSE_END=============================================
20  * ====================================================================
21  */
22 package org.onap.music.main;
23
24 import java.io.FileNotFoundException;
25 import java.io.FileReader;
26 import java.io.UnsupportedEncodingException;
27 import java.security.InvalidKeyException;
28 import java.security.NoSuchAlgorithmException;
29 import java.security.SecureRandom;
30 import java.util.Scanner;
31
32 import javax.crypto.BadPaddingException;
33 import javax.crypto.Cipher;
34 import javax.crypto.IllegalBlockSizeException;
35 import javax.crypto.NoSuchPaddingException;
36 import javax.crypto.spec.IvParameterSpec;
37 import javax.crypto.spec.SecretKeySpec;
38
39 import org.apache.commons.codec.binary.Base64;
40 import org.apache.commons.lang3.ArrayUtils;
41 import org.onap.music.eelf.logging.EELFLoggerDelegate;
42
43 public class CipherUtil {
44
45
46         /**
47          * Default key.
48          */
49         private static String keyString = null;
50
51         private static final String ALGORITHM = "AES";
52         private static final String ALGORYTHM_DETAILS = ALGORITHM + "/CBC/PKCS5PADDING";
53         private static final int BLOCK_SIZE = 128;
54         @SuppressWarnings("unused")
55         private static SecretKeySpec secretKeySpec;
56         private static IvParameterSpec ivspec;
57         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CipherUtil.class);
58         /**
59          * @deprecated Please use {@link #encryptPKC(String)} to encrypt the text.
60          * 
61          *             Encrypts the text using the specified secret key.
62          * 
63          * @param plainText
64          *            Text to encrypt
65          * @param secretKey
66          *            Key to use for encryption
67          * @return encrypted version of plain text.
68          * @
69          *             if any encryption step fails
70          *
71          */
72         @Deprecated
73         public static String encrypt(String plainText, String secretKey)  {
74                 String encryptedString = null;
75                 try {
76                         byte[] encryptText = plainText.getBytes("UTF-8");
77                         byte[] rawKey = Base64.decodeBase64(secretKey);
78                         SecretKeySpec sKeySpec = new SecretKeySpec(rawKey, "AES");
79                         Cipher cipher = Cipher.getInstance("AES");
80                         cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
81                         encryptedString = Base64.encodeBase64String(cipher.doFinal(encryptText));
82                 } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException
83                                 | NoSuchPaddingException | UnsupportedEncodingException ex) {
84                 }
85                 return encryptedString;
86         }
87
88         /**
89          * @deprecated Please use {@link #encryptPKC(String)} to encrypt the text.
90          *             Encrypts the text using the secret key in key.properties file.
91          * 
92          * @param plainText
93          *            Text to encrypt
94          * @return Encrypted Text
95          * @
96          *             if any decryption step fails
97          */
98         @Deprecated
99         public static String encrypt(String plainText)  {
100                 return CipherUtil.encrypt(plainText, keyString);
101         }
102
103         /**
104          * Encrypts the text using a secret key.
105          * 
106          * @param plainText
107          *            Text to encrypt
108          * @return Encrypted Text
109          * @
110          *             if any decryption step fails
111          */
112         public static String encryptPKC(String plainText)  {
113                 return CipherUtil.encryptPKC(plainText, keyString);
114         }
115
116         /**
117          * 
118          * @deprecated Please use {@link #decryptPKC(String)} to Decryption the text.
119          * 
120          *             Decrypts the text using the specified secret key.
121          * 
122          * @param encryptedText
123          *            Text to decrypt
124          * @param secretKey
125          *            Key to use for decryption
126          * @return plain text version of encrypted text
127          * @
128          *             if any decryption step fails
129          * 
130          */
131         @Deprecated
132         public static String decrypt(String encryptedText, String secretKey)  {
133                 String encryptedString = null;
134                 try {
135                         byte[] rawKey = Base64.decodeBase64(secretKey);
136                         SecretKeySpec sKeySpec = new SecretKeySpec(rawKey, "AES");
137                         byte[] encryptText = Base64.decodeBase64(encryptedText.getBytes("UTF-8"));
138                         Cipher cipher = Cipher.getInstance("AES");
139                         cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
140                         encryptedString = new String(cipher.doFinal(encryptText));
141                 } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException
142                                 | NoSuchPaddingException | UnsupportedEncodingException ex) {
143                 }
144                 return encryptedString;
145         }
146
147         private static SecretKeySpec getSecretKeySpec() {
148                 byte[] key = Base64.decodeBase64(keyString);
149                 return new SecretKeySpec(key, ALGORITHM);
150         }
151
152         private static SecretKeySpec getSecretKeySpec(String keyString) {
153                 byte[] key = Base64.decodeBase64(keyString);
154                 return new SecretKeySpec(key, ALGORITHM);
155         }
156
157         /**
158          * Encrypt the text using the secret key in key.properties file
159          * 
160          * @param value
161          * @return The encrypted string
162          * @throws BadPaddingException
163          * @
164          *             In case of issue with the encryption
165          */
166         public static String encryptPKC(String value, String skey)  {
167                 Cipher cipher = null;
168                 byte[] iv = null, finalByte = null;
169
170                 try {
171                         cipher = Cipher.getInstance(ALGORYTHM_DETAILS, "SunJCE");
172
173                         SecureRandom r = SecureRandom.getInstance("SHA1PRNG");
174                         iv = new byte[BLOCK_SIZE / 8];
175                         r.nextBytes(iv);
176                         ivspec = new IvParameterSpec(iv);
177                         cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(skey), ivspec);
178                         finalByte = cipher.doFinal(value.getBytes());
179
180                 } catch (Exception ex) {
181                         
182                 }
183                 return Base64.encodeBase64String(ArrayUtils.addAll(iv, finalByte));
184         }
185
186         /**
187          * Decrypts the text using the secret key in key.properties file.
188          * 
189          * @param message
190          *            The encrypted string that must be decrypted using the ecomp
191          *            Encryption Key
192          * @return The String decrypted
193          * @
194          *             if any decryption step fails
195          */
196         public static String decryptPKC(String message, String skey)  {
197                 byte[] encryptedMessage = Base64.decodeBase64(message);
198                 Cipher cipher;
199                 byte[] decrypted = null;
200                 try {
201                         cipher = Cipher.getInstance(ALGORYTHM_DETAILS, "SunJCE");
202                         ivspec = new IvParameterSpec(ArrayUtils.subarray(encryptedMessage, 0, BLOCK_SIZE / 8));
203                         byte[] realData = ArrayUtils.subarray(encryptedMessage, BLOCK_SIZE / 8, encryptedMessage.length);
204                         cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(skey), ivspec);
205                         decrypted = cipher.doFinal(realData);
206
207                 } catch (Exception ex) {
208                         
209                         
210                 }
211
212                 return new String(decrypted);
213         }
214
215         /**
216          * @deprecated Please use {@link #decryptPKC(String)} to Decrypt the text.
217          * 
218          *             Decrypts the text using the secret key in key.properties file.
219          * 
220          * @param encryptedText
221          *            Text to decrypt
222          * @return Decrypted text
223          * @
224          *             if any decryption step fails
225          */
226         @Deprecated
227         public static String decrypt(String encryptedText)  {
228                 return CipherUtil.decrypt(encryptedText, keyString);
229         }
230
231         /**
232          * 
233          * Decrypts the text using the secret key in key.properties file.
234          * 
235          * @param encryptedText
236          *            Text to decrypt
237          * @return Decrypted text
238          * @
239          *             if any decryption step fails
240          */
241         public static String decryptPKC(String encryptedText)  {
242                 return CipherUtil.decryptPKC(encryptedText, keyString);
243         }
244
245         
246         public static void readAndSetKeyString() {
247                 try {
248                         Scanner in = new Scanner(new FileReader("/opt/app/music/etc/properties.txt"));
249                         StringBuilder sb = new StringBuilder();
250                         while(in.hasNext()) {
251                             sb.append(in.next());
252                         }
253                         in.close();
254                         keyString = sb.toString();
255                 } catch (FileNotFoundException e) {
256                         logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
257                 }
258         }
259
260         /*public static void main(String[] args)  {
261
262                 System.out.println("Encrypted password: "+encryptPKC("cassandra"));
263
264                 System.out.println("Decrypted password: "+decryptPKC("dDhqAp5/RwZbl9yRSZg15fN7Qul9eiE/JFkKemtTib0="));
265                 System.out.println("Decrypted password: "+decryptPKC("I/dOtD/YYzBStbtOYhKuUUyPHSW2G9ZzdSyB8bJp4vk="));
266                 System.out.println("Decrypted password: "+decryptPKC("g7zJqg74dLsH/fyL7I75b4eySy3pbMS2xVqkrB5lDl8="));
267         }*/
268
269 }