· 7 years ago · May 14, 2018, 08:10 PM
1final byte[] kek = // ... generate SHA-256 key via `PBKDF2WithHmacSHA256`
2SecretKey sKey = new SecretKeySpec(kek, "AES");
3
4Cipher c = Cipher.getInstance("AESWrap", "SunJCE");
5c.init(Cipher.WRAP_MODE, sKey);
6
7byte[] bytes = privateValue.getBytes();
8SecretKeySpec wk = new SecretKeySpec(bytes, "AES");
9byte[] result = c.wrap(wk);
10
11byte[] salt = .... // 32 random bytes...
12byte[] kek = ... // PBKDF2WithHmacSHA256 hash from private value and salt
13
14SecretKey sKey = new SecretKeySpec(kek, "AES");
15Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
16
17SecureRandom rng = new SecureRandom();
18byte[] ivBytes = new byte[c.getBlockSize()];
19rng.nextBytes(ivBytes);
20IvParameterSpec iv = new IvParameterSpec(ivBytes);
21
22c.init(Cipher.WRAP_MODE, sKey, iv);
23SecretKeySpec wk = new SecretKeySpec(privateValue.getBytes(), "AES");
24byte[] result = c.wrap(wk); // wrapped private value
25
26byte[] kek = ... // PBKDF2WithHmacSHA256 hash from private value and previous salt
27
28SecretKey sKey = new SecretKeySpec(kek, "AES");
29Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
30
31IvParameterSpec iv = new IvParameterSpec(parsed.getIv()); // previously created iv
32c.init(Cipher.UNWRAP_MODE, sKey, iv);
33
34SecretKeySpec wk = new SecretKeySpec(privateValue.getBytes(), "AES");
35Key result = c.unwrap(parsed.getKey(), "AES", Cipher.SECRET_KEY);
36
37byte[] pv = result.getEncoded(); // unwrapped private value
38
39// --- key pair with private key for testing
40KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
41gen.initialize(4096);
42KeyPair kp = gen.generateKeyPair();
43
44// --- create KEK
45final byte[] kek = new byte[16]; // test value
46SecretKey sKey = new SecretKeySpec(kek, "AES");
47
48// --- the cipher, not a special wrapping algorithm
49Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
50
51// --- create IV
52// not really necessary because the modulus comes first, but nicer
53SecureRandom rng = new SecureRandom();
54byte[] ivBytes = new byte[c.getBlockSize()];
55rng.nextBytes(ivBytes);
56IvParameterSpec iv = new IvParameterSpec(ivBytes);
57
58// --- init & wrap by normal encryption
59c.init(Cipher.WRAP_MODE, sKey, iv);
60byte[] result = c.wrap(kp.getPrivate());