11d464a85c19842f5b97979e71f3725f6af74b3f
[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
25 import java.security.GeneralSecurityException;
26 import java.security.NoSuchAlgorithmException;
27
28 import javax.crypto.Cipher;
29 import javax.crypto.spec.SecretKeySpec;
30
31 import org.onap.so.logger.MessageEnum;
32 import org.onap.so.logger.MsoLogger;
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     public static final String AES = "AES";
44     private static final String CLOUD_KEY = "aa3871669d893c7fb8abbcda31b88b4f";
45     /**
46      * encrypt a value and generate a keyfile
47      * if the keyfile is not found then a new one is created
48      * 
49      * @throws GeneralSecurityException
50      */
51     public static String encrypt (String value, String keyString) throws GeneralSecurityException {
52         SecretKeySpec sks = getSecretKeySpec (keyString);
53         Cipher cipher = Cipher.getInstance (CryptoUtils.AES);
54         cipher.init (Cipher.ENCRYPT_MODE, sks, cipher.getParameters ());
55         byte[] encrypted = cipher.doFinal (value.getBytes ());
56         return byteArrayToHexString (encrypted);
57     }
58
59     /**
60      * decrypt a value
61      * 
62      * @throws GeneralSecurityException
63      */
64     public static String decrypt (String message, String keyString) throws GeneralSecurityException {
65         SecretKeySpec sks = getSecretKeySpec (keyString);
66         Cipher cipher = Cipher.getInstance (CryptoUtils.AES);
67         cipher.init (Cipher.DECRYPT_MODE, sks);
68         byte[] decrypted = cipher.doFinal (hexStringToByteArray (message));
69         return new String (decrypted);
70     }
71
72     /**
73      * decrypt a value or return defaultValue
74      * 
75      */
76     public static String decryptProperty (String prop, String defaultValue, String encryptionKey) {
77                  try {
78                          return CryptoUtils.decrypt(prop, encryptionKey);                       
79                  }      
80                  catch (GeneralSecurityException e) {
81                          LOGGER.debug("Security exception", e);
82                  }
83                  return defaultValue;
84         }
85     
86     public static String encryptCloudConfigPassword(String message) {
87         try {
88                 return CryptoUtils.encrypt(message, CryptoUtils.CLOUD_KEY);
89             } catch (GeneralSecurityException e) {
90                 LOGGER.error (MessageEnum.RA_GENERAL_EXCEPTION, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in encryptPassword", e);
91                 return null;
92             }
93     }
94     public static String decryptCloudConfigPassword(String message) {
95         try {
96                 return CryptoUtils.decrypt(message, CryptoUtils.CLOUD_KEY);
97             } catch (GeneralSecurityException e) {
98                 LOGGER.error (MessageEnum.RA_GENERAL_EXCEPTION, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in encryptPassword", e);
99                 return null;
100             }
101     }
102     private static SecretKeySpec getSecretKeySpec (String keyString) throws NoSuchAlgorithmException {
103         byte[] key = hexStringToByteArray (keyString);
104         SecretKeySpec sks = new SecretKeySpec (key, CryptoUtils.AES);
105         return sks;
106     }
107
108     public static String byteArrayToHexString (byte[] b) {
109         StringBuilder sb = new StringBuilder(b.length * 2);
110         for (byte aB : b) {
111             int v = aB & 0xff;
112             if (v < 16) {
113                 sb.append('0');
114             }
115             sb.append(Integer.toHexString(v));
116         }
117         return sb.toString ().toUpperCase ();
118     }
119
120     private static byte[] hexStringToByteArray (String s) {
121         byte[] b = new byte[s.length () / 2];
122         for (int i = 0; i < b.length; i++) {
123             int index = i * 2;
124             int v = Integer.parseInt (s.substring (index, index + 2), 16);
125             b[i] = (byte) v;
126         }
127         return b;
128     }
129 }