Springboot 2.0 upgrade
[so.git] / common / src / main / java / org / onap / so / utils / CryptoUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 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.onap.so.utils;
22
23
24 import org.onap.so.logger.MessageEnum;
25 import org.onap.so.logger.MsoLogger;
26
27 import javax.crypto.Cipher;
28 import javax.crypto.spec.GCMParameterSpec;
29 import javax.crypto.spec.SecretKeySpec;
30 import java.security.GeneralSecurityException;
31 import java.security.SecureRandom;
32 import java.util.Arrays;
33
34
35 /**
36  * CryptoUtils adapted from RTTP client.
37  * 
38  */
39 public final class CryptoUtils {
40
41     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, CryptoUtils.class);
42
43     private static final String AES = "AES";
44     private static final String CLOUD_KEY = "aa3871669d893c7fb8abbcda31b88b4f";
45     private static final int GCM_TAG_LENGTH = 16;
46     private static final int GCM_IV_LENGTH = 12;
47     private static final String AES_GCM_NO_PADDING = "AES/GCM/NoPadding";
48
49     /**
50      * encrypt a value and generate a keyfile
51      * if the keyfile is not found then a new one is created
52      * 
53      * @throws GeneralSecurityException
54      */
55     public static String encrypt (String value, String keyString) throws GeneralSecurityException {
56         SecretKeySpec sks = getSecretKeySpec (keyString);
57         Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING);
58         byte[] initVector = new byte[GCM_IV_LENGTH];
59         (new SecureRandom()).nextBytes(initVector);
60         GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, initVector);
61         cipher.init(Cipher.ENCRYPT_MODE, sks, spec);
62         byte[] encoded = value.getBytes(java.nio.charset.StandardCharsets.UTF_8);
63         byte[] cipherText = new byte[initVector.length + cipher.getOutputSize(encoded.length)];
64         System.arraycopy(initVector, 0, cipherText, 0, initVector.length);
65         cipher.doFinal(encoded, 0, encoded.length, cipherText, initVector.length);
66         return byteArrayToHexString(cipherText);
67     }
68
69     /**
70      * decrypt a value
71      * 
72      * @throws GeneralSecurityException
73      */
74     public static String decrypt (String message, String keyString) throws GeneralSecurityException {
75         SecretKeySpec sks = getSecretKeySpec (keyString);
76         byte[] cipherText = hexStringToByteArray(message);
77         Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING);
78         byte[] initVector = Arrays.copyOfRange(cipherText, 0, GCM_IV_LENGTH);
79         GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, initVector);
80         cipher.init(Cipher.DECRYPT_MODE, sks, spec);
81         byte[] plaintext = cipher.doFinal(cipherText, GCM_IV_LENGTH, cipherText.length - GCM_IV_LENGTH);
82         return new String(plaintext);
83     }
84     
85     public static String encryptCloudConfigPassword(String message) {
86         try {
87                 return CryptoUtils.encrypt(message, CLOUD_KEY);
88             } catch (GeneralSecurityException e) {
89                 LOGGER.error (MessageEnum.RA_GENERAL_EXCEPTION, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in encryptPassword", e);
90                 return null;
91             }
92     }
93     public static String decryptCloudConfigPassword(String message) {
94         try {
95                 return CryptoUtils.decrypt(message, CLOUD_KEY);
96             } catch (GeneralSecurityException e) {
97                 LOGGER.error (MessageEnum.RA_GENERAL_EXCEPTION, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in encryptPassword", e);
98                 return null;
99             }
100     }
101     private static SecretKeySpec getSecretKeySpec (String keyString) {
102         byte[] key = hexStringToByteArray (keyString);
103         return new SecretKeySpec (key, AES);
104     }
105
106     public static String byteArrayToHexString (byte[] b) {
107         StringBuilder sb = new StringBuilder(b.length * 2);
108         for (byte aB : b) {
109             int v = aB & 0xff;
110             if (v < 16) {
111                 sb.append('0');
112             }
113             sb.append(Integer.toHexString(v));
114         }
115         return sb.toString ().toUpperCase ();
116     }
117
118     private static byte[] hexStringToByteArray (String s) {
119         byte[] b = new byte[s.length () / 2];
120         for (int i = 0; i < b.length; i++) {
121             int index = i * 2;
122             int v = Integer.parseInt (s.substring (index, index + 2), 16);
123             b[i] = (byte) v;
124         }
125         return b;
126     }
127 }