1616import java .util .Optional ;
1717
1818
19+ /**
20+ * Utility class for encrypting and decrypting values using HMAC signatures
21+ */
1922public class Encryptor {
2023 /**
2124 * The algorithm used for signing
@@ -34,9 +37,12 @@ public class Encryptor {
3437 /**
3538 * Creates a new {@link Encryptor}
3639 *
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
4046 */
4147 public Encryptor (@ NotNull String algorithm , @ NotNull byte [] secret , @ Nullable Duration maxAge ) throws NoSuchAlgorithmException , InvalidKeyException {
4248 this .algorithm = algorithm ;
@@ -68,6 +74,14 @@ private byte[] getSignature(@NotNull String payload) {
6874 }
6975 }
7076
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+ */
7185 @ Nullable
7286 public String encrypt (@ NotNull Object value ) {
7387 final String payload = value + ":" + System .currentTimeMillis ();
@@ -77,6 +91,13 @@ public String encrypt(@NotNull Object value) {
7791 return Base64 .getUrlEncoder ().withoutPadding ().encodeToString (token .getBytes (StandardCharsets .UTF_8 ));
7892 }
7993
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+ */
80101 @ Nullable
81102 public String decrypt (@ NotNull String token ) {
82103 // Decode token
0 commit comments