HMAC 加密算法
import java.nio.charset.StandardCharsets;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
public class HMACUtil {
public static final String TYPE_MD5 = "HmacMD5";
public static final String TYPE_SHA1 = "HmacSHA1";
public static final String TYPE_HASH256 = "HmacSHA256";
public static final String TYPE_HASH512 = "HmacSHA512";
public static String encryptMd5(String content, String key) {
return encrypt(content, key, TYPE_MD5);
}
public static String encryptHash256(String content, String key) {
return encrypt(content, key, TYPE_HASH256);
}
public static String encryptHash512(String content, String key) {
return encrypt(content, key, TYPE_HASH512);
}
public static String encrypt(String content, String key, String type) {
try {
return encryptHmac(content.getBytes(StandardCharsets.UTF_8), Hex.decodeHex(key), type);
} catch (DecoderException e) {
throw new RuntimeException(e);
}
}
// HMAC MD5 加密
public static String encryptHmacMD5(byte[] data, byte[] key) {
return encryptHmac(data, key, TYPE_MD5);
}
// HMAC SHA256 加密
public static String encryptHmacSHA256(byte[] data, byte[] key) {
return encryptHmac(data, key, TYPE_HASH256);
}
// HMAC SHA521 加密
public static String encryptHmacSHA512(byte[] data, byte[] key) {
return encryptHmac(data, key, TYPE_HASH512);
}
// 基础MAC 算法
public static String encryptHmac(byte[] data, byte[] key, String type) {
try {
// 1、还原密钥
SecretKey secretKey = new SecretKeySpec(key, type);
// 2、创建MAC对象
Mac mac = Mac.getInstance(type);
// 3、设置密钥
mac.init(secretKey);
// 4、数据加密
byte[] bytes = mac.doFinal(data);
// 5、生成数据
return Hex.encodeHexString(bytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String getHmacKeyStr(String type) {
return Hex.encodeHexString(getHmacKey(type));
}
// 获取 HMAC Key
public static byte[] getHmacKey(String type) {
try {
// 1、创建密钥生成器
KeyGenerator keyGenerator = KeyGenerator.getInstance(type);
// 2、产生密钥
SecretKey secretKey = keyGenerator.generateKey