It was a bit hard to find correct HMAC SHA384 code for JAVA, so here to share my example code, hope can save some time to try and error.
You can test this example in here
import java.security.NoSuchAlgorithmException;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Mac;
public class SecureUtils {
private static String bytesToHex(final byte[] hash) {
final StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
final String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException {
final String nonce = "test"; //your key
final String message = "Password"; //your plain txt
SecretKeySpec signingKey = new SecretKeySpec(nonce.getBytes(),"HmacSHA384");
final Mac mac = Mac.getInstance("HmacSHA384");
try{
mac.init(signingKey);
System.out.println(bytesToHex(mac.doFinal(message.getBytes())));
}
catch(Exception ex){ }
}
}
Check result with online hmac generator
Those code modify from stackoverflow HMAC SHA-384 in Java
No comments:
Post a Comment