61b3cd51cfae48668faf9784c73c9ec4490a987f
[appc.git] / appc-config / appc-flow-controller / provider / src / main / java / org / onap / appc / flow / controller / utils / EncryptionTool.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
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  *
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.flow.controller.utils;
26
27
28 import java.security.Provider;
29 import java.security.Provider.Service;
30 import java.security.Security;
31
32 import org.jasypt.contrib.org.apache.commons.codec_1_3.binary.Base64;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 /**
37  * This class is used to encapsulate the encryption and decryption support in one place and to
38  * provide a utility to encrypt and decrypt data.
39  */
40 public class EncryptionTool {
41
42     /**
43      * The prefix we insert onto any data we encrypt so that we can tell if it is encrpyted later and
44      * therefore decrypt it
45      */
46     public static final String ENCRYPTED_VALUE_PREFIX = "enc:";
47
48     /**
49      * The instance of the encryption utility object
50      */
51     private static EncryptionTool instance = null;
52
53     /**
54      * The logger for this class.
55      */
56     private static final Logger LOG = LoggerFactory.getLogger(EncryptionTool.class);
57
58     /**
59      * The secret passphrase (PBE) that we use to perform encryption and decryption. The algorithm we
60      * are using is a symmetrical cipher.
61      */
62     private static char[] secret = {'C', '_', 'z', 'l', '!', 'K', '!', '4', '?', 'O', 'z', 'E', 'K', 'E', '>', 'U', 'R',
63             '/', '%', 'Y', '\\', 'f', 'b', '"', 'e', 'n', '{', '"', 'l', 'U', 'F', '+', 'E', '\'', 'R', 'T', 'p', '1',
64             'V', '4', 'l', 'a', '9', 'w', 'v', '5', 'Z', '#', 'i', 'V', '"', 'd', 'l', '!', 'L', 'M', 'g', 'L', 'Q',
65             '{', 'v', 'v', 'K', 'V'};
66
67
68
69     /**
70      * Get an instance of the EncryptionTool
71      *
72      * @return The encryption tool to be used
73      */
74     public static final synchronized EncryptionTool getInstance() {
75         if (instance == null) {
76             instance = new EncryptionTool();
77         }
78         return instance;
79     }
80
81     /**
82      * Create the EncryptionTool instance
83      */
84     private EncryptionTool() {
85
86         StringBuilder sb = new StringBuilder("Found the following security algorithms:");
87         for (Provider p : Security.getProviders()) {
88             for (Service s : p.getServices()) {
89                 String algo = s.getAlgorithm();
90                 sb.append(String.format("%n -Algorithm [ %s ] in provider [ %s ] and service [ %s ]", algo, p.getName(),
91                         s.getClassName()));
92             }
93         }
94         if (LOG.isDebugEnabled()) {
95             LOG.debug(sb.toString());
96         }
97     }
98
99     /**
100      * Decrypt the provided encrypted text
101      *
102      * @param cipherText THe cipher text to be decrypted. If the ciphertext is not encrypted, then it is
103      *        returned as is.
104      * @return the clear test of the (possibly) encrypted value. The original value if the string is not
105      *         encrypted.
106      */
107     public synchronized String decrypt(String cipherText) {
108         if (isEncrypted(cipherText)) {
109             String encValue = cipherText.substring(ENCRYPTED_VALUE_PREFIX.length());
110             byte[] plainByte = Base64.decodeBase64(encValue.getBytes());
111             byte[] decryptByte = xorWithSecret(plainByte);
112             return new String(decryptByte);
113         } else {
114             return cipherText;
115         }
116
117     }
118
119     /**
120      * Encrypt the provided clear text
121      *
122      * @param clearText The clear text to be encrypted
123      * @return the encrypted text. If the clear text is empty (null or zero length), then an empty
124      *         string is returned. If the clear text is already encrypted, it is not encrypted again and
125      *         is returned as is. Otherwise, the clear text is encrypted and returned.
126      */
127     public synchronized String encrypt(String clearText) {
128         if (clearText != null) {
129             byte[] encByte = xorWithSecret(clearText.getBytes());
130             String encryptedValue = new String(Base64.encodeBase64(encByte));
131             return ENCRYPTED_VALUE_PREFIX + encryptedValue;
132         } else {
133             return null;
134         }
135     }
136
137     /**
138      * Is a value encrypted? A value is considered to be encrypted if it begins with the
139      * {@linkplain #ENCRYPTED_VALUE_PREFIX encrypted value prefix}.
140      *
141      * @param value the value to check.
142      * @return true/false;
143      */
144     private static boolean isEncrypted(final String value) {
145         return value != null && value.startsWith(ENCRYPTED_VALUE_PREFIX);
146     }
147
148     /**
149      * XORs the input byte array with the secret key, padding 0x0 to the end of the secret key if the
150      * input is longer and returns a byte array the same size as input
151      *
152      * @param inp The byte array to be XORed with secret
153      * @return A byte array the same size as inp or null if input is null.
154      */
155     private byte[] xorWithSecret(byte[] inp) {
156         if (inp == null) {
157             return new byte[0];
158         }
159
160         byte[] secretBytes = new String(secret).getBytes();
161         int size = inp.length;
162
163         byte[] out = new byte[size];
164         for (int i = 0; i < size; i++) {
165             out[i] = (byte) ((inp[i]) ^ (secretBytes[i % secretBytes.length]));
166         }
167         return out;
168     }
169
170 }