using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Linq;
namespace PaymentSDK
{
/// 签名验证类
///
public class CheckSignature
{
///
/// 在网站没有提供Token(或传入为null)的情况下的默认Token,建议在网站中进行配置。
///
public const string Token = "weixin";
///
/// 检查签名是否正确
///
///
/// 需要提供:Timestamp、Nonce、Token
///
public static bool Check(string signature, PostModel postModel)
{
return Check(signature, postModel.Timestamp, postModel.Nonce, postModel.Token);
}
///
/// 检查签名是否正确
///
///
///
///
///
///
public static bool Check(string signature, string timestamp, string nonce, string token = null)
{
return signature == GetSignature(timestamp, nonce, token);
}
///
/// 返回正确的签名
///
/// 需要提供:Timestamp、Nonce、Token
///
public static string GetSignature(PostModel postModel)
{
return GetSignature(postModel.Timestamp, postModel.Nonce, postModel.Token);
}
///
/// 返回正确的签名
///
///
///
///
///
public static string GetSignature(string timestamp, string nonce, string token = null)
{
token = token ?? Token;
var arr = new[] { token, timestamp, nonce }.OrderBy(z => z).ToArray();
var arrString = string.Join("", arr);
//var enText = FormsAuthentication.HashPasswordForStoringInConfigFile(arrString, "SHA1");//使用System.Web.Security程序集
var sha1 = SHA1.Create();
var sha1Arr = sha1.ComputeHash(Encoding.UTF8.GetBytes(arrString));
StringBuilder enText = new StringBuilder();
foreach (var b in sha1Arr)
{
enText.AppendFormat("{0:x2}", b);
}
return enText.ToString();
}
}
public class PostModel
{
public string Timestamp { get; set; }
public string Nonce { get; set; }
public string Token { get; set; }
}
}