-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRootKeyManager.java
More file actions
52 lines (42 loc) · 1.95 KB
/
RootKeyManager.java
File metadata and controls
52 lines (42 loc) · 1.95 KB
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
package ftn.security.minikms.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.util.Base64;
@Service
public class RootKeyManager {
private static final java.security.SecureRandom RNG = new java.security.SecureRandom();
private final SecretKey rootKey;
public RootKeyManager(@Value("${ROOT_KEY}") String base64Key) {
if (base64Key == null || base64Key.isEmpty()) {
throw new IllegalArgumentException("ROOT_KEY environment variable is not set or empty");
}
byte[] raw = Base64.getDecoder().decode(base64Key);
this.rootKey = new SecretKeySpec(raw, "AES");
}
public byte[] wrap(byte[] plaintextKey, byte[] aad) throws GeneralSecurityException {
var iv = new byte[12];
RNG.nextBytes(iv);
var c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, rootKey, new GCMParameterSpec(128, iv));
if (aad != null && aad.length > 0) c.updateAAD(aad);
var ct = c.doFinal(plaintextKey);
var out = new byte[iv.length + ct.length];
System.arraycopy(iv, 0, out, 0, iv.length);
System.arraycopy(ct, 0, out, iv.length, ct.length);
return out;
}
public byte[] unwrap(byte[] blob, byte[] aad) throws GeneralSecurityException {
if (blob.length < 12 + 16) throw new GeneralSecurityException("Blob too short");
var iv = java.util.Arrays.copyOfRange(blob, 0, 12);
var ct = java.util.Arrays.copyOfRange(blob, 12, blob.length);
var c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.DECRYPT_MODE, rootKey, new GCMParameterSpec(128, iv));
if (aad != null && aad.length > 0) c.updateAAD(aad);
return c.doFinal(ct);
}
}