summaryrefslogtreecommitdiffstats
path: root/security-util-lib/src/main/java/org/onap/sdc/security/CipherUtil.java
blob: ba8665a98873e8ce5cd1a88dea293105884add8b (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
/*-
 * ============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 java.security.SecureRandom;

import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.ArrayUtils;
import org.onap.sdc.security.logging.elements.ErrorLogOptionalData;
import org.onap.sdc.security.logging.elements.LogFieldsMdcHandler;
import org.onap.sdc.security.logging.enums.EcompLoggerErrorCode;
import org.onap.sdc.security.logging.wrappers.Logger;

public class CipherUtil {
    private static Logger log = Logger.getLogger( CipherUtil.class.getName());
    private static final String ALGORITHM = "AES";
    private static final String ALGORYTHM_DETAILS = ALGORITHM + "/GCM/NoPadding";
    private static final String CIPHER_PROVIDER = "SunJCE";

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

    private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
    private static final String ALGORITHM_NAME = "SHA1PRNG";

    /**
     * Encrypt the text using the secret key in key.properties file
     *
     * @param value string to encrypt
     * @return The encrypted string
     * @throws CipherUtilException
     *             In case of issue with the encryption
     */
    public static String encryptPKC(String value, String base64key) throws CipherUtilException {
        Cipher cipher;
        byte[] iv = new byte[GCM_IV_LENGTH];
        byte[] finalByte;
        try {
            cipher = Cipher.getInstance(ALGORYTHM_DETAILS, CIPHER_PROVIDER);
            SecureRandom secureRandom = SecureRandom.getInstance(ALGORITHM_NAME);
            secureRandom.nextBytes(iv);
            GCMParameterSpec spec =
                new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, iv);
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(base64key), spec);
            finalByte = cipher.doFinal(value.getBytes());

        } catch (Exception ex) {
            log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, LogFieldsMdcHandler.getInstance().getServiceName(), new ErrorLogOptionalData(), "encrypt failed", ex);
            throw new CipherUtilException(ex);
        }
        return Base64.encodeBase64String(addAll(iv, finalByte));
    }

    /**
     * Decrypts the text using the secret key in key.properties file.
     *
     * @param message
     *            The encrypted string that must be decrypted using the ONAP Portal
     *            Encryption Key
     * @return The String decrypted
     * @throws CipherUtilException
     *             if any decryption step fails
     */

    public static String decryptPKC(String message, String base64key) throws CipherUtilException {
        byte[] encryptedMessage = Base64.decodeBase64(message);
        Cipher cipher;
        byte[] decrypted;
        try {
            cipher = Cipher.getInstance(ALGORYTHM_DETAILS, CIPHER_PROVIDER);
            byte[] initVector = Arrays.copyOfRange(encryptedMessage, 0, GCM_IV_LENGTH);
            GCMParameterSpec spec =
                new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, initVector);
            byte[] realData = subarray(encryptedMessage, GCM_IV_LENGTH, encryptedMessage.length);
            cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(base64key), spec);
            decrypted = cipher.doFinal(realData);

        } catch (Exception ex) {
            log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, LogFieldsMdcHandler.getInstance().getServiceName(), new ErrorLogOptionalData(),"decrypt failed", ex);
            throw new CipherUtilException(ex);
        }
        return new String(decrypted);
    }

    private static SecretKeySpec getSecretKeySpec(String keyString) {
        byte[] key = Base64.decodeBase64(keyString);
        return new SecretKeySpec(key, ALGORITHM);
    }

    private static byte[] addAll(byte[] array1, byte[] array2) {
        if (array1 == null) {
            return ArrayUtils.clone(array2);
        } else if (array2 == null) {
            return ArrayUtils.clone(array1);
        } else {
            byte[] joinedArray = new byte[array1.length + array2.length];
            System.arraycopy(array1, 0, joinedArray, 0, array1.length);
            System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
            return joinedArray;
        }
    }

    private static byte[] subarray(byte[] array, int startIndexInclusive, int endIndexExclusive) {
        if (array == null) {
            return null;
        } else {
            if (startIndexInclusive < 0) {
                startIndexInclusive = 0;
            }

            if (endIndexExclusive > array.length) {
                endIndexExclusive = array.length;
            }

            int newSize = endIndexExclusive - startIndexInclusive;
            if (newSize <= 0) {
                return EMPTY_BYTE_ARRAY;
            } else {
                byte[] subarray = new byte[newSize];
                System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
                return subarray;
            }
        }
    }
}