package com.hxzk.util;
|
|
import org.bouncycastle.crypto.RuntimeCryptoException;
|
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
|
import javax.crypto.Mac;
|
import javax.crypto.SecretKey;
|
import javax.crypto.spec.SecretKeySpec;
|
import java.io.IOException;
|
import java.security.Security;
|
import java.text.ParseException;
|
import java.util.Base64;
|
|
public class HmacSHA256 {
|
/**
|
* @param content 加密内容
|
* @param secret 加密key
|
* 使用 HMAC-SHA256 以 secret为密钥(字符串形式,非原始二进制),以 content为消息,计算消息摘要,再进行base64编码处理,得到 signature
|
* @return
|
*/
|
public static String encrytSHA256(String content, String secret) {
|
|
try {
|
Security.addProvider(new BouncyCastleProvider());
|
SecretKey secretKey = new SecretKeySpec(secret.getBytes("UTF8"), "HmacSHA256");
|
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
|
mac.init(secretKey);
|
byte[] digest = mac.doFinal(content.getBytes("UTF-8"));
|
//return new HexBinaryAdapter().marshal(digest).toLowerCase();
|
// .toLowerCase()小写
|
// .toUpperCase();大写
|
|
//加密后用base64再加密
|
String signature = Base64.getEncoder().encodeToString(digest);
|
} catch (Exception e) {
|
throw new RuntimeCryptoException("加密异常");
|
}
|
|
return content;
|
}
|
public static void main(String[] args) throws ParseException, IOException {
|
System.out.println(encrytSHA256("加密内容", "key"));
|
}
|
}
|