summaryrefslogtreecommitdiffstats
path: root/security-util-lib/src/main/java/org/onap/sdc/security/SecurityUtil.java
blob: eb67813374442106ac337fb11b4ec67ddf9b6577 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.sdc.security;

import static java.nio.charset.StandardCharsets.UTF_8;

import fj.data.Either;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.GCMParameterSpec;
import org.onap.sdc.security.logging.enums.EcompLoggerErrorCode;
import org.onap.sdc.security.logging.wrappers.Logger;

public class SecurityUtil {

    private static final Logger LOG = Logger.getLogger(SecurityUtil.class);

    public static final SecurityUtil INSTANCE = new SecurityUtil();
    public static final String ALGORITHM = "AES";
    public static final String CHARSET = UTF_8.name();

    public static final int GCM_TAG_LENGTH = 16;
    public static final int GCM_IV_LENGTH = 12;

    private static final Key secKey = generateKey(ALGORITHM);

    private SecurityUtil() {
    }

    public static SecretKey generateKey(String algorithm) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance(algorithm);
            kgen.init(128);
            return kgen.generateKey();
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e.toString());
        }
    }

    // obfuscates key prefix -> **********
    public String obfuscateKey(String sensitiveData) {

        if (sensitiveData == null) {
            return null;
        }
        int len = sensitiveData.length();
        StringBuilder builder = new StringBuilder(sensitiveData);
        for (int i = 0; i < len / 2; i++) {
            builder.setCharAt(i, '*');
        }
        return builder.toString();
    }

    //@formatter:off
    /**
     * @param strDataToEncrypt - plain string to encrypt Encrypt the Data
     *                         a. Declare / Initialize the Data. Here the data is of type String
     *                         b. Convert the Input Text to Bytes
     *                         c. Encrypt the bytes using doFinal method
     */
    //@formatter:on
    public static Either<String, String> encrypt(String strDataToEncrypt) {
        try {
            byte[] ciphertext = null;
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            byte[] initVector = new byte[GCM_IV_LENGTH];
            new SecureRandom().nextBytes(initVector);
            GCMParameterSpec spec =
                new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, initVector);
            cipher.init(Cipher.ENCRYPT_MODE, secKey, spec);
            byte[] encoded = strDataToEncrypt.getBytes(java.nio.charset.StandardCharsets.UTF_8);
            ciphertext = Arrays.copyOf(initVector, initVector.length + cipher.getOutputSize(encoded.length));
            // Perform encryption
            cipher.doFinal(encoded, 0, encoded.length, ciphertext, initVector.length);
            String strCipherText = new String(Base64.getMimeEncoder().encode(ciphertext), CHARSET);
            return Either.left(strCipherText);
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidAlgorithmParameterException e) {
            LOG.warn(
                EcompLoggerErrorCode.PERMISSION_ERROR,
                "cannot encrypt data unknown algorithm or missing encoding for {}",
                secKey.getAlgorithm());
        } catch (InvalidKeyException e) {
            LOG.warn(
                EcompLoggerErrorCode.PERMISSION_ERROR,
                "invalid key recieved - > {} | {}",
                new String(Base64.getDecoder().decode(secKey.getEncoded())),
                e.getMessage());
        } catch (IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e) {
            LOG.warn(
                EcompLoggerErrorCode.PERMISSION_ERROR,
                "bad algorithm definition (Illegal Block Size or padding), please review you algorithm block&padding",
                e.getMessage());
        } catch (ShortBufferException e) {
            LOG.warn(
                EcompLoggerErrorCode.PERMISSION_ERROR,
                "the given output buffer is too small to hold the result",
                e.getMessage());
        }
        return Either.right("Cannot encrypt " + strDataToEncrypt);
    }

    //@formatter:off
    /**
     * Decrypt the Data
     *
     * @param byteCipherText  - should be valid bae64 input in the length of 16bytes
     * @param isBase64Decoded - is data already base64 encoded&aligned to 16 bytes
     *                        a. Initialize a new instance of Cipher for Decryption (normally don't reuse the same object)
     *                        b. Decrypt the cipher bytes using doFinal method
     */
    //@formatter:on
    public static Either<String, String> decrypt(byte[] byteCipherText, boolean isBase64Decoded) {
        try {
            if (isBase64Decoded) {
                byteCipherText = Base64.getDecoder().decode(byteCipherText);
            }
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            byte[] initVector = Arrays.copyOfRange(byteCipherText, 0, GCM_IV_LENGTH);
            GCMParameterSpec spec =
                new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, initVector);
            cipher.init(Cipher.DECRYPT_MODE, secKey, spec);
            byte[] plaintext =
                cipher.doFinal(byteCipherText, GCM_IV_LENGTH, byteCipherText.length - GCM_IV_LENGTH);
            String strDecryptedText = new String(plaintext);
            return Either.left(strDecryptedText);
        } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
            /* None of these exceptions should be possible if precond is met. */
            LOG.warn(
                EcompLoggerErrorCode.PERMISSION_ERROR,
                "cannot decrypt data, unknown algorithm or missing encoding for {}",
                secKey.getAlgorithm());
        } catch (InvalidKeyException e) {
            LOG.warn(
                EcompLoggerErrorCode.PERMISSION_ERROR,
                "invalid key recieved - > {} | {}",
                new String(Base64.getDecoder().decode(secKey.getEncoded())),
                e.getMessage());
        } catch (IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e) {
            /* these indicate corrupt or malicious ciphertext */
            LOG.warn(
                EcompLoggerErrorCode.PERMISSION_ERROR,
                "bad algorithm definition (Illegal Block Size or padding), please review you algorithm block&padding",
                e.getMessage());
        }
        return Either.right("Decrypt FAILED");
    }

    public Either<String, String> decrypt(String byteCipherText) {
        try {
            return decrypt(byteCipherText.getBytes(CHARSET), true);
        } catch (UnsupportedEncodingException e) {
            LOG.warn(
                EcompLoggerErrorCode.PERMISSION_ERROR,
                "Missing encoding for {} | {} ",
                secKey.getAlgorithm(),
                e.getMessage());
        }
        return Either.right("Decrypt FAILED");
    }
}