签名验签
本文档主要讲解签名算法
一、签名计算过程
1、将请求body的json字符串,按照HmacSHA1算法计算签名,算法密钥为appSecret
2、将HmacSHA1加密之后的结果转BASE64编码
3、签名算法计算出来的字符串为签名值sign
- 样例:
请求body:{"offset":0,"size":10,"fetchChild":1,"status":0,"timestamp":1606813480832} 签名密钥appSecret = ysUxwof!$CS9@i4V9RE6 签名结果sign = SfTybq8t1sayu67LuLPw9NtiVX4%3D
二、签名算法demo
java版
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import org.apache.commons.codec.binary.Base64;
/**
* 签名算法
*
* @param content 签名明文
* @param appSecret 应用密钥
* @return 签名信息
* @throws Exception
*/
public static String hmacSha1Encrypt(String content, String appSecret) throws Exception {
byte[] keyBytes = appSecret.getBytes(StandardCharsets.UTF_8);
SecretKeySpec localSecretKeySpec = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac localMac = Mac.getInstance("HmacSHA1");
localMac.init(localSecretKeySpec);
byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
localMac.update(contentBytes);
return URLEncoder.encode(Base64.encodeBase64String(localMac.doFinal()),"utf-8");
}
php版
function hash_hmac($content, $appSecret)
{
retrun base64_encode(hash_hmac("sha1", utf8_decode($content), utf8_decode($appSecret), true));
}
python版
注:字符串参数需使用双引号,否则会导致签名验证失败
def hash_hmac(content, appSecret):
hmac_code = hmac.new(appSecret.encode(), content.encode(), sha1).digest()
return base64.b64encode(hmac_code)
c#版
using System;
using System.Text;
using System.Security.Cryptography;
public class Test
{
public static void Main()
{
Console.WriteLine(HMACSHA1Text("{\"offset\":0,\"size\":10,\"fetchChild\":1,\"status\":0,\"timestamp\":1606813480832}","ysUxwof!$CS9@i4V9RE6"));
}
public static string HMACSHA1Text(string text, string key)
{
byte[] byteData = Encoding.ASCII.GetBytes(text);
byte[] byteKey = Encoding.ASCII.GetBytes(key);
HMACSHA1 hmac = new HMACSHA1(byteKey);
return Convert.ToBase64String(hmac.ComputeHash(byteData));
}
}