37 lines
1.1 KiB
Java
37 lines
1.1 KiB
Java
package com.gh.common.util;
|
|
|
|
import java.security.InvalidKeyException;
|
|
import java.security.NoSuchAlgorithmException;
|
|
|
|
import javax.crypto.Mac;
|
|
import javax.crypto.spec.SecretKeySpec;
|
|
|
|
public class HMACUtils {
|
|
|
|
public static String encrypt(String data, String key) {
|
|
try {
|
|
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA256");
|
|
Mac mac = Mac.getInstance("HmacSHA256");
|
|
mac.init(signingKey);
|
|
return byte2hex(mac.doFinal(data.getBytes()));
|
|
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
|
|
e.printStackTrace();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private static String byte2hex(byte[] ciphertext) {
|
|
StringBuilder builder = new StringBuilder();
|
|
String stmp;
|
|
for (int i = 0; ciphertext != null && i < ciphertext.length; i++) {
|
|
stmp = Integer.toHexString(ciphertext[i] & 0XFF);
|
|
if (stmp.length() == 1) {
|
|
builder.append('0');
|
|
}
|
|
builder.append(stmp);
|
|
}
|
|
return builder.toString().toLowerCase();
|
|
}
|
|
|
|
}
|