5496f0d8755100d11d1dcbd12c121cb25d8d9419
[policy/engine.git] / PolicyEngineUtils / src / main / java / org / onap / policy / utils / CryptoUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * PolicyEngineUtils
4  * ================================================================================
5  * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
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  * ============LICENSE_END=========================================================
19  */
20 package org.onap.policy.utils;
21
22 import java.nio.charset.StandardCharsets;
23 import java.security.AlgorithmParameters;
24 import java.security.InvalidAlgorithmParameterException;
25 import java.security.InvalidKeyException;
26 import java.security.NoSuchAlgorithmException;
27 import java.security.Key;
28 import java.util.Base64;
29
30 import javax.crypto.BadPaddingException;
31 import javax.crypto.Cipher;
32 import javax.crypto.IllegalBlockSizeException;
33 import javax.crypto.NoSuchPaddingException;
34 import javax.crypto.spec.SecretKeySpec;
35 import javax.xml.bind.DatatypeConverter;
36
37 import org.onap.policy.common.logging.flexlogger.FlexLogger;
38 import org.onap.policy.common.logging.flexlogger.Logger;
39
40 public class CryptoUtils {
41         private static final Logger LOGGER = FlexLogger.getLogger(CryptoUtils.class);
42         private static final String CIPHER_TYPE = "AES/CBC/PKCS5Padding";
43         private static Key mKey = null;
44         private static AlgorithmParameters mAlgParm = null;
45
46         static {
47                 //the hadcoded key is to be removed in a future iteration
48                 try {
49                         String kval = "bmpybWJrbGN4dG9wbGF3Zg==";
50                         String algp = "BBBpbml0VmVjVGhpc0lzVGhl";
51
52                         byte[] kvalb = DatatypeConverter.parseBase64Binary(kval);
53                         byte[] algb = DatatypeConverter.parseBase64Binary(algp);
54
55                         mKey = new SecretKeySpec(kvalb, "AES");
56
57                         mAlgParm = AlgorithmParameters.getInstance("AES");
58                         mAlgParm.init(algb, "ASN.1");
59
60                 } catch (Exception ex) {
61                         throw new ExceptionInInitializerError(ex);
62                 }
63         }
64
65         private CryptoUtils() {
66                 // Private Constructor
67         }
68
69         /**
70          * Decrypt txt.
71          *
72          * @param encryptedTxt
73          *            text to be decrypted, Base 64 UrlEncoded
74          * @return the byte[]
75          * @throws NoSuchAlgorithmException
76          *             the no such algorithm exception
77          * @throws NoSuchPaddingException
78          *             the no such padding exception
79          * @throws InvalidAlgorithmParameterException
80          *             the invalid algorithm parameter exception
81          * @throws InvalidKeyException
82          *             the invalid key exception
83          * @throws IllegalBlockSizeException
84          *             the illegal block size exception
85          * @throws BadPaddingException
86          *             the bad padding exception
87          */
88         public static byte[] decryptTxt(String encryptedTxt)
89                         throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException,
90                         InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
91                 Cipher cipher = Cipher.getInstance(CIPHER_TYPE);
92                 cipher.init(Cipher.DECRYPT_MODE, mKey, mAlgParm);
93
94                 return cipher.doFinal(Base64.getUrlDecoder().decode(encryptedTxt.getBytes(StandardCharsets.UTF_8)));
95         }
96
97         /**
98          * Decrypt txt.
99          *
100          * @param encryptedTxt
101          *            text to be decrypted, Base 64 UrlEncoded
102          * @param mKey
103          *            the key as Base 64
104          * @return the byte[]
105          * @throws NoSuchAlgorithmException
106          *             the no such algorithm exception
107          * @throws NoSuchPaddingException
108          *             the no such padding exception
109          * @throws InvalidAlgorithmParameterException
110          *             the invalid algorithm parameter exception
111          * @throws InvalidKeyException
112          *             the invalid key exception
113          * @throws IllegalBlockSizeException
114          *             the illegal block size exception
115          * @throws BadPaddingException
116          *             the bad padding exception
117          */
118         public static byte[] decryptTxt(String encryptedTxt, String base64BinaryKey)
119                         throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException,
120                         InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
121
122                 byte[] keyValueByte = DatatypeConverter.parseBase64Binary(base64BinaryKey);
123                 Key paramKey = new SecretKeySpec(keyValueByte, "AES");
124                 Cipher cipher = Cipher.getInstance(CIPHER_TYPE);
125                 cipher.init(Cipher.DECRYPT_MODE, paramKey, mAlgParm);
126
127                 return cipher.doFinal(Base64.getUrlDecoder().decode(encryptedTxt.getBytes(StandardCharsets.UTF_8)));
128         }
129
130         /**
131          * Decrypt txt, no exceptions thrown.
132          *
133          * @param encryptedTxt
134          *            text to be decrypted, Base 64 UrlEncoded
135          * @return the decrypted text, or the original text if it could not be
136          *         decrypted
137          */
138         public static byte[] decryptTxtNoEx(String encryptedTxt) {
139
140                 try {
141                         if (encryptedTxt == null || encryptedTxt.isEmpty()) {
142                                 LOGGER.error("decryptTxtNoEx: Input param encryptedTxt is not valid");
143                                 return new byte[0];
144                         }
145                         return decryptTxt(encryptedTxt);
146                 } catch (Exception e) {
147                         try {
148                                 LOGGER.error("decryptTxtNoEx: Exception while decryption : " + e);
149                                 return (encryptedTxt != null) ? encryptedTxt.getBytes(StandardCharsets.UTF_8) : new byte[0];
150                         } catch (Exception e1) {
151                                 LOGGER.error("decryptTxtNoEx: Exception on sending default : " + e1);
152                                 return new byte[0];
153                         }
154                 }
155         }
156         
157         /**
158          * Decrypt txt, no exceptions thrown.
159          *
160          * @param encryptedTxt
161          *            text to be decrypted, Base 64 UrlEncoded
162          * @return the decrypted text, or the original text if it could not be
163          *         decrypted
164          */
165         public static String decryptTxtNoExStr(String encryptedTxt) {
166                         return new String(decryptTxtNoEx(encryptedTxt), StandardCharsets.UTF_8);
167         }
168
169         /**
170          * Encrypt txt.
171          *
172          * @param plainTxt
173          *            the plain txt
174          * @return the encrypted string
175          * @throws NoSuchPaddingException
176          *             the no such padding exception
177          * @throws InvalidAlgorithmParameterException
178          *             the invalid algorithm parameter exception
179          * @throws NoSuchAlgorithmException
180          *             the no such algorithm exception
181          * @throws InvalidKeyException
182          *             the invalid key exception
183          * @throws IllegalBlockSizeException
184          *             the illegal block size exception
185          * @throws BadPaddingException
186          *             the bad padding exception
187          */
188         public static String encryptTxt(byte[] plainTxt)
189                         throws NoSuchPaddingException, InvalidAlgorithmParameterException,
190                         NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
191
192                 Cipher cipher = Cipher.getInstance(CIPHER_TYPE);
193                 cipher.init(Cipher.ENCRYPT_MODE, mKey, mAlgParm);
194
195                 byte[] encryption = cipher.doFinal(plainTxt);
196                 return new String(Base64.getUrlEncoder().encode(encryption), StandardCharsets.UTF_8);
197         }
198
199         /**
200          * Encrypt txt.
201          *
202          * @param plainTxt
203          *            the plain txt to be encrypted
204          * @param base64BinaryKey
205          *            the key as lexical representation of Base64 Binary
206          * @return the encrypted string
207          * @throws NoSuchPaddingException
208          *             the no such padding exception
209          * @throws InvalidAlgorithmParameterException
210          *             the invalid algorithm parameter exception
211          * @throws NoSuchAlgorithmException
212          *             the no such algorithm exception
213          * @throws InvalidKeyException
214          *             the invalid key exception
215          * @throws IllegalBlockSizeException
216          *             the illegal block size exception
217          * @throws BadPaddingException
218          *             the bad padding exception
219          */
220         public static String encryptTxt(byte[] plainTxt, String base64BinaryKey)
221                         throws NoSuchPaddingException, InvalidAlgorithmParameterException,
222                         NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
223
224                 byte[] keyValueByte = DatatypeConverter.parseBase64Binary(base64BinaryKey);
225                 Key paramKey = new SecretKeySpec(keyValueByte, "AES");
226                 Cipher cipher = Cipher.getInstance(CIPHER_TYPE);
227                 cipher.init(Cipher.ENCRYPT_MODE, paramKey, mAlgParm);
228
229                 byte[] encryption = cipher.doFinal(plainTxt);
230                 return new String(Base64.getMimeEncoder().encode(encryption), StandardCharsets.UTF_8);
231         }
232
233         /**
234          * Encrypt txt, no exceptions thrown
235          *
236          * @param plainTxt
237          *            the plain txt to be encrypted
238          * @return the encrypted String , or the original text if it could not be
239          *         encrypted
240          */
241         public static String encryptTxtNoEx(byte[] plainTxt) {
242
243                 if (plainTxt == null || plainTxt.length == 0) {
244                         LOGGER.error("encryptTxtNoEx: Input param plainTxt is not valid");
245                         return "";
246                 }
247
248                 try {
249                         return encryptTxt(plainTxt);
250                 } catch (Exception e) {
251                         LOGGER.error("encryptTxtNoEx: Exception while decryption : " + e);
252                         return new String(plainTxt, StandardCharsets.UTF_8);
253                 }
254         }
255
256 }