Added oparent to sdc main
[sdc.git] / openecomp-be / backend / openecomp-sdc-security-util / src / main / java / org / openecomp / sdc / securityutil / CipherUtil.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 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
21 package org.openecomp.sdc.securityutil;
22
23 import java.security.SecureRandom;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 import javax.crypto.Cipher;
28 import javax.crypto.spec.IvParameterSpec;
29 import javax.crypto.spec.SecretKeySpec;
30 import org.apache.commons.codec.binary.Base64;
31
32 public class CipherUtil {
33     private static Logger log = LoggerFactory.getLogger( CipherUtil.class.getName());
34     private static final String ALGORITHM = "AES";
35     private static final String ALGORYTHM_DETAILS = ALGORITHM + "/CBC/PKCS5PADDING";
36     private static final String CIPHER_PROVIDER = "SunJCE";
37     private static final int BLOCK_SIZE = 128;
38     private static final int BYTE_SIZE = 8;
39     private static final int IV_SIZE = BLOCK_SIZE / BYTE_SIZE;
40     private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
41     private static final String ALGORITHM_NAME = "SHA1PRNG";
42
43     /**
44      * Encrypt the text using the secret key in key.properties file
45      *
46      * @param value string to encrypt
47      * @return The encrypted string
48      * @throws CipherUtilException
49      *             In case of issue with the encryption
50      */
51     public static String encryptPKC(String value, String base64key) throws CipherUtilException {
52         Cipher cipher;
53         byte[] iv = new byte[IV_SIZE];
54         byte[] finalByte;
55         try {
56             cipher = Cipher.getInstance(ALGORYTHM_DETAILS, CIPHER_PROVIDER);
57             SecureRandom secureRandom = SecureRandom.getInstance(ALGORITHM_NAME);
58             secureRandom.nextBytes(iv);
59             IvParameterSpec ivspec = new IvParameterSpec(iv);
60             cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(base64key), ivspec);
61             finalByte = cipher.doFinal(value.getBytes());
62
63         } catch (Exception ex) {
64             log.error("encrypt failed", ex);
65             throw new CipherUtilException(ex);
66         }
67         return Base64.encodeBase64String(addAll(iv, finalByte));
68     }
69
70     /**
71      * Decrypts the text using the secret key in key.properties file.
72      *
73      * @param message
74      *            The encrypted string that must be decrypted using the ONAP Portal
75      *            Encryption Key
76      * @return The String decrypted
77      * @throws CipherUtilException
78      *             if any decryption step fails
79      */
80
81     public static String decryptPKC(String message, String base64key) throws CipherUtilException {
82         byte[] encryptedMessage = Base64.decodeBase64(message);
83         Cipher cipher;
84         byte[] decrypted;
85         try {
86             cipher = Cipher.getInstance(ALGORYTHM_DETAILS, CIPHER_PROVIDER);
87             IvParameterSpec ivspec = new IvParameterSpec(subarray(encryptedMessage, 0, IV_SIZE));
88             byte[] realData = subarray(encryptedMessage, IV_SIZE, encryptedMessage.length);
89             cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(base64key), ivspec);
90             decrypted = cipher.doFinal(realData);
91
92         } catch (Exception ex) {
93             log.error("decrypt failed", ex);
94             throw new CipherUtilException(ex);
95         }
96         return new String(decrypted);
97     }
98
99     private static SecretKeySpec getSecretKeySpec(String keyString) {
100         byte[] key = Base64.decodeBase64(keyString);
101         return new SecretKeySpec(key, ALGORITHM);
102     }
103
104     private static byte[] clone(byte[] array) {
105         return array == null ? null : array.clone();
106     }
107
108     private static byte[] addAll(byte[] array1, byte[] array2) {
109         if (array1 == null) {
110             return clone(array2);
111         } else if (array2 == null) {
112             return clone(array1);
113         } else {
114             byte[] joinedArray = new byte[array1.length + array2.length];
115             System.arraycopy(array1, 0, joinedArray, 0, array1.length);
116             System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
117             return joinedArray;
118         }
119     }
120
121     private static byte[] subarray(byte[] array, int startIndexInclusive, int endIndexExclusive) {
122         if (array == null) {
123             return null;
124         } else {
125             if (startIndexInclusive < 0) {
126                 startIndexInclusive = 0;
127             }
128
129             if (endIndexExclusive > array.length) {
130                 endIndexExclusive = array.length;
131             }
132
133             int newSize = endIndexExclusive - startIndexInclusive;
134             if (newSize <= 0) {
135                 return EMPTY_BYTE_ARRAY;
136             } else {
137                 byte[] subarray = new byte[newSize];
138                 System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
139                 return subarray;
140             }
141         }
142     }
143 }