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