Skip to content

Instantly share code, notes, and snippets.

@navono
Created October 5, 2020 02:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navono/eae8b60993feaade410e734dfc4c1ef3 to your computer and use it in GitHub Desktop.
Save navono/eae8b60993feaade410e734dfc4c1ef3 to your computer and use it in GitHub Desktop.
HMAC in Java
package hello;
import javax.crypto.Mac;
import javax.crypto.spec.*;
public class HMAC {
public void hash() {
try {
String secret = "salt";// 加密使用的key
String message = "1";// 需要加密的字符串(本项目是 "{uuid}_{timestamp}" )
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
String hash = byteArrayToHexString(sha256_HMAC.doFinal(message.getBytes()));// 重点
System.out.println(hash);
}
catch (Exception e){
System.out.println("Error");
}
}
@org.jetbrains.annotations.NotNull
private static String byteArrayToHexString(byte[] b) {
StringBuilder hs = new StringBuilder();
String stmp;
for (int n = 0; b!=null && n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1)
hs.append('0');
hs.append(stmp);
}
return hs.toString().toLowerCase();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment