1 import javax.crypto.Cipher;
2 import javax.crypto.spec.GCMParameterSpec;
3 import javax.crypto.spec.SecretKeySpec;
4 import java.security.GeneralSecurityException;
5 import java.security.SecureRandom;
6 import java.util.Arrays;
10 private static final String AES = "AES";
11 private static final int GCM_TAG_LENGTH = 16;
12 private static final int GCM_IV_LENGTH = 12;
13 private static final String AES_GCM_NO_PADDING = "AES/GCM/NoPadding";
15 public static void main(String[] args) {
16 if(args.length != 2) {
17 System.out.println("Usage: java Crypto value_to_encrypt key");
18 System.out.println("exit(1)");
22 String value = args[0];
24 String encrypted = encryptCloudConfigPassword(value, key);
25 System.out.println(encrypted);
29 * encrypt a value and generate a keyfile
30 * if the keyfile is not found then a new one is created
32 * @throws GeneralSecurityException
34 public static String encrypt (String value, String keyString) throws GeneralSecurityException {
35 SecretKeySpec sks = getSecretKeySpec (keyString);
36 Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING);
37 byte[] initVector = new byte[GCM_IV_LENGTH];
38 (new SecureRandom()).nextBytes(initVector);
39 GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, initVector);
40 cipher.init(Cipher.ENCRYPT_MODE, sks, spec);
41 byte[] encoded = value.getBytes(java.nio.charset.StandardCharsets.UTF_8);
42 byte[] cipherText = new byte[initVector.length + cipher.getOutputSize(encoded.length)];
43 System.arraycopy(initVector, 0, cipherText, 0, initVector.length);
44 cipher.doFinal(encoded, 0, encoded.length, cipherText, initVector.length);
45 return byteArrayToHexString(cipherText);
48 public static String encryptCloudConfigPassword(String message, String key) {
50 return Crypto.encrypt(message, key);
51 } catch (GeneralSecurityException e) {
56 private static SecretKeySpec getSecretKeySpec (String keyString) {
57 byte[] key = hexStringToByteArray (keyString);
58 return new SecretKeySpec (key, AES);
61 public static String byteArrayToHexString (byte[] b) {
62 StringBuilder sb = new StringBuilder(b.length * 2);
68 sb.append(Integer.toHexString(v));
70 return sb.toString ().toUpperCase ();
73 private static byte[] hexStringToByteArray (String s) {
74 byte[] b = new byte[s.length () / 2];
75 for (int i = 0; i < b.length; i++) {
77 int v = Integer.parseInt (s.substring (index, index + 2), 16);