· 7 years ago · Jan 18, 2019, 02:04 AM
1import javax.crypto.Mac;
2import javax.crypto.spec.SecretKeySpec;
3import java.security.InvalidKeyException;
4import java.security.NoSuchAlgorithmException;
5import java.util.Base64;
6
7public class HmacSha256 {
8
9 private static final String SECRET = "secret-here";
10
11 public static String generateHmacSha256(String value) {
12 try {
13 Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
14 SecretKeySpec secret_key = new SecretKeySpec(SECRET.getBytes(), "HmacSHA256");
15 sha256_HMAC.init(secret_key);
16 byte[] s53 = sha256_HMAC.doFinal(value.getBytes());
17 String hash = Base64.getEncoder().encodeToString(s53);
18 return hash;
19 } catch (IllegalStateException | InvalidKeyException | NoSuchAlgorithmException ex) {
20 throw new RuntimeException("HMAC", ex);
21 }
22
23 }
24
25}