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