sha256_HMAC加密
message 消息 secret 秘钥
对参数按照key=value的格式,生成字符串
string sign = Encrypt("key", mchkey); //mchkey为商户秘钥key
public static string Encrypt(string key, string value,Dictionary<string,object> dictionary)
{
StringBuilder sb = new StringBuilder();
ArrayList akeys = new ArrayList(this.parameters.Keys);
akeys.Sort();
foreach (string k in akeys)
{
var v = (string)this.parameters[k];
if (null != v && "".CompareTo(v) != 0 && "sign".CompareTo(k) != 0 && "key".CompareTo(k) != 0)
{
sb.Append(k + "=" + v + "&");
}
}
sb.Append(key + "=" + value);
string sign = Hmac_SHA256.GetHash(sb.ToString(), value);
return sign;
}
HMACSHA256 加密
public static string GetHash(string message, string secret)
{
string result = "";
var enc = Encoding.UTF8;
byte[]
baText2BHashed = enc.GetBytes(message),
baSalt = enc.GetBytes(secret);
System.Security.Cryptography.HMACSHA256 hasher = new HMACSHA256(baSalt);
byte[] baHashedText = hasher.ComputeHash(baText2BHashed);
result = string.Join("", baHashedText.ToList().Select(b => b.ToString("x2")).ToArray());
return result.ToUpper();//一定要转化为大写
}