在做微信接口開發的過程中, 有時候發現會提示簽名校驗失敗, 一模一樣的簽名邏輯就是有些接口跑步通, 找了一圈發現挺坑的;
原來是有些接口的signType簽名類型有區別, 有些接口signType要求是MD5,有的要求是HMAC-SHA256, 其實這兩種算法都是
hash算法的一種沒有太大的差別, 但是生成的簽名結果會不一樣;
下面附上HMAC-SHA256算法代碼
package com.lh.micro.datasource.util;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class HMACSHA256 {
/**
* 將加密後的字節數組轉換成字符串
*
* @param b 字節數組
* @return 字符串
*/
public 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 加密後字符串
*/
public 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;
}
}
歷史文章:
JAVA微信企業付款到零錢(十分鐘搞定)
微信授權獲取用戶openId的方法和步驟
一個微信號同時支持多個環境網頁授權
微信兩種簽名算法MD5和HMAC-SHA256