-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathSecretService.java
More file actions
63 lines (56 loc) · 1.97 KB
/
SecretService.java
File metadata and controls
63 lines (56 loc) · 1.97 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
53
54
55
56
57
58
59
60
61
62
63
package com.linkedin.metadata.secret;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class SecretService {
private final String _secret;
public SecretService(final String secret) {
_secret = secret;
}
public String encrypt(String value) {
try {
SecretKeySpec secretKey = null;
byte[] key;
MessageDigest sha = null;
try {
key = _secret.getBytes(StandardCharsets.UTF_8);
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
throw new RuntimeException("Failed to encrypt value using provided secret!", e);
}
}
public String decrypt(String encryptedValue) {
try {
SecretKeySpec secretKey = null;
byte[] key;
MessageDigest sha = null;
try {
key = _secret.getBytes(StandardCharsets.UTF_8);
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(encryptedValue)));
} catch (Exception e) {
throw new RuntimeException("Failed to decrypt value using provided secret!", e);
}
}
}