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