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