2 * ============LICENSE_START=======================================================
\r
4 * ================================================================================
\r
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
\r
6 * ================================================================================
\r
7 * Licensed under the Apache License, Version 2.0 (the "License");
\r
8 * you may not use this file except in compliance with the License.
\r
9 * You may obtain a copy of the License at
\r
11 * http://www.apache.org/licenses/LICENSE-2.0
\r
13 * Unless required by applicable law or agreed to in writing, software
\r
14 * distributed under the License is distributed on an "AS IS" BASIS,
\r
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
16 * See the License for the specific language governing permissions and
\r
17 * limitations under the License.
\r
18 * ============LICENSE_END=========================================================
\r
21 package org.openecomp.mso.bpmn.common.util;
\r
24 import java.security.GeneralSecurityException;
\r
25 import java.security.NoSuchAlgorithmException;
\r
27 import javax.crypto.Cipher;
\r
28 import javax.crypto.spec.SecretKeySpec;
\r
30 //Need to add BPM error handler
\r
33 * CryptoUtils adapted from RTTP client.
\r
36 public class CryptoUtils {
\r
38 public static final String AES = "AES";
\r
41 * encrypt a value and generate a keyfile
\r
42 * if the keyfile is not found then a new one is created
\r
43 * @throws GeneralSecurityException
\r
45 public static String encrypt(String value, String keyString) throws GeneralSecurityException
\r
47 SecretKeySpec sks = getSecretKeySpec(keyString);
\r
48 Cipher cipher = Cipher.getInstance(CryptoUtils.AES);
\r
49 cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
\r
50 byte[] encrypted = cipher.doFinal(value.getBytes());
\r
51 return byteArrayToHexString(encrypted);
\r
56 * @throws GeneralSecurityException
\r
58 public static String decrypt(String message, String keyString) throws GeneralSecurityException
\r
60 SecretKeySpec sks = getSecretKeySpec(keyString);
\r
61 Cipher cipher = Cipher.getInstance(CryptoUtils.AES);
\r
62 cipher.init(Cipher.DECRYPT_MODE, sks);
\r
63 byte[] decrypted = cipher.doFinal(hexStringToByteArray(message));
\r
64 return new String(decrypted);
\r
67 private static SecretKeySpec getSecretKeySpec(String keyString) throws NoSuchAlgorithmException
\r
69 byte [] key = hexStringToByteArray(keyString);
\r
70 SecretKeySpec sks = new SecretKeySpec(key, CryptoUtils.AES);
\r
75 private static String byteArrayToHexString(byte[] b){
\r
76 StringBuilder sb = new StringBuilder(b.length * 2);
\r
82 sb.append(Integer.toHexString(v));
\r
84 return sb.toString().toUpperCase();
\r
87 private static byte[] hexStringToByteArray(String s) {
\r
88 byte[] b = new byte[s.length() / 2];
\r
89 for (int i = 0; i < b.length; i++){
\r
91 int v = Integer.parseInt(s.substring(index, index + 2), 16);
\r