为了验证结果,可以在线加密解密网站上验证:http://encode.chahuo.com/
直接上demo类,其中核心算法可以抽离到util类,这里写main方法打印出的结果与网站是的内容进行验证。
public static void main(String[] args) throws Exception {
System.out.println(HelloController.sha256_HMAC("api_key=d554d071885feeaa05f4087e93c9409d&api_time=1535598970&key=46964aeddfe512a4fb0b8789de20035c",
"46964aeddfe512a4fb0b8789de20035c").toUpperCase());
}
/**
* 将加密后的字节数组转换成字符串
*
* @param b 字节数组
* @return 字符串
*/
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();
}
/**
* sha256_HMAC加密
* @param message 消息
* @param secret 秘钥
* @return 加密后字符串
*/
private static String sha256_HMAC(String message, String secret) {
String hash = "";
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
hash = byteArrayToHexString(bytes);
} catch (Exception e) {
System.out.println("Error HmacSHA256 ===========" + e.getMessage());
}
return hash;
}
console打印:
网站是的结果为:
结论:完全一致(只不过有大小写的区别,代码可修改)