16
16
import java .util .Optional ;
17
17
18
18
19
+ /**
20
+ * Utility class for encrypting and decrypting values using HMAC signatures
21
+ */
19
22
public class Encryptor {
20
23
/**
21
24
* The algorithm used for signing
@@ -34,9 +37,12 @@ public class Encryptor {
34
37
/**
35
38
* Creates a new {@link Encryptor}
36
39
*
37
- * @param algorithm {@link #algorithm}
38
- * @param secret {@link #secret}
39
- * @param maxAge {@link #maxAge}
40
+ * @param algorithm {@link #algorithm}
41
+ * @param secret {@link #secret}
42
+ * @param maxAge {@link #maxAge}
43
+ *
44
+ * @throws NoSuchAlgorithmException if the specified algorithm is not available
45
+ * @throws InvalidKeyException if the provided secret is invalid
40
46
*/
41
47
public Encryptor (@ NotNull String algorithm , @ NotNull byte [] secret , @ Nullable Duration maxAge ) throws NoSuchAlgorithmException , InvalidKeyException {
42
48
this .algorithm = algorithm ;
@@ -68,6 +74,14 @@ private byte[] getSignature(@NotNull String payload) {
68
74
}
69
75
}
70
76
77
+ /**
78
+ * Encrypts a value by creating a signed token that includes the value and a timestamp
79
+ * <br>The token format is {@code base64(value:timestamp:signature)}
80
+ *
81
+ * @param value the value to encrypt, will be converted to string using {@link Object#toString()}
82
+ *
83
+ * @return the encrypted token, or {@code null} if an error occurred during signature generation
84
+ */
71
85
@ Nullable
72
86
public String encrypt (@ NotNull Object value ) {
73
87
final String payload = value + ":" + System .currentTimeMillis ();
@@ -77,6 +91,13 @@ public String encrypt(@NotNull Object value) {
77
91
return Base64 .getUrlEncoder ().withoutPadding ().encodeToString (token .getBytes (StandardCharsets .UTF_8 ));
78
92
}
79
93
94
+ /**
95
+ * Decrypts a token by verifying its signature and timestamp
96
+ *
97
+ * @param token the token to decrypt
98
+ *
99
+ * @return the original value if the token is valid and not expired, otherwise {@code null}
100
+ */
80
101
@ Nullable
81
102
public String decrypt (@ NotNull String token ) {
82
103
// Decode token
0 commit comments