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