using System.Security.Cryptography; using System.Text; using Zncy.CloudCar.WeChat.Service.Models; namespace Zncy.CloudCar.WeChat.Service.Utilities { /// /// 签名验证类 /// public class CheckSignature { /// 在网站没有提供Token(或传入为null)的情况下的默认Token,建议在网站中进行配置。 public const string Token = "weixin"; /// 检查签名是否正确 /// /// 需要提供:Timestamp、Nonce、Token /// public static bool Check(string signature, PostModel postModel) => Check(signature, postModel.Timestamp, postModel.Nonce, postModel.Token); /// 检查签名是否正确 /// /// /// /// /// #pragma warning disable CS8625 // 无法将 null 字面量转换为非 null 的引用类型。 public static bool Check(string signature, string timestamp, string nonce, string token = null) => signature == GetSignature(timestamp, nonce, token); #pragma warning restore CS8625 // 无法将 null 字面量转换为非 null 的引用类型。 /// 返回正确的签名 /// 需要提供:Timestamp、Nonce、Token /// public static string GetSignature(PostModel postModel) => GetSignature(postModel.Timestamp, postModel.Nonce, postModel.Token); /// 返回正确的签名 /// /// /// /// #pragma warning disable CS8625 // 无法将 null 字面量转换为非 null 的引用类型。 public static string GetSignature(string timestamp, string nonce, string token = null) #pragma warning restore CS8625 // 无法将 null 字面量转换为非 null 的引用类型。 { token = token ?? "weixin"; string s = string.Join("", ((IEnumerable)new string[3] { token, timestamp, nonce }).OrderBy(z => z).ToArray()); byte[] hash = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(s)); StringBuilder stringBuilder = new StringBuilder(); foreach (byte num in hash) stringBuilder.AppendFormat("{0:x2}", num); return stringBuilder.ToString(); } } }