Created
October 5, 2020 02:54
-
-
Save navono/eae8b60993feaade410e734dfc4c1ef3 to your computer and use it in GitHub Desktop.
HMAC in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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