//微信的应答
public static bool Sign(HttpResponseMessage response)
{
try
{
var Serial = "";//验签的微信支付平台证书序列号/微信支付公钥ID
if (response.Headers.TryGetValues("Wechatpay-Serial", out var Values))
{
// 将值集合拼接成字符串
Serial = string.Join(", ", Values);
}
string str_Timestamp = "";
string str_Nonce = "";
string str_Signature = "";
if (response.Headers.TryGetValues("Wechatpay-Timestamp", out var dateValues))
{
str_Timestamp = string.Join(", ", dateValues);//应答时间戳
}
if (response.Headers.TryGetValues("Wechatpay-Nonce", out var dateValues2))
{
str_Nonce = string.Join(", ", dateValues2);//应答随机串
}
if (response.Headers.TryGetValues("Wechatpay-Signature", out var dateValues3))
{
str_Signature = string.Join(", ", dateValues3);//应答签名
}
var retString = response.Content.ReadAsStringAsync().Result;//原始报文主体
string message = string.Format("{0}\n{1}\n{2}\n", str_Timestamp, str_Nonce, retString);
var isVerified = WxHelper.VerifySignature(message, str_Signature);
WriteTextLogHelper.WriteTextLog("公钥验签,", Serial + " * " + str_Timestamp + " * " + str_Nonce + " * " + str_Signature + " * " + isVerified, DateTime.Now);
return isVerified;
}
catch (Exception ex)
{
throw;
}
}
//验证
public static bool VerifySignature(string message, string signature)
{
try
{
string KeyPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/") + "\\Common\\WebChat\\pub_key.pem";//公钥文件保存地址
var KeyParameter = LoadKey(KeyPath);//读取公钥
if (KeyParameter == null)
{
return false;
}
// 初始化 RSA 引擎用于签名
var signer = SignerUtilities.GetSigner("SHA-256withRSA");//创建SHA256withRSA签名算法
signer.Init(false, KeyParameter);// 初始化签名者 注意这里是false
// 更新要签名的数据
var dataBytes = Encoding.UTF8.GetBytes(message);
signer.BlockUpdate(dataBytes, 0, dataBytes.Length);
var signatureBytes = Convert.FromBase64String(signature);// 解析:要验证的签名
return signer.VerifySignature(signatureBytes);// 验证签名
}
catch (Exception ex)// 处理异常
{
return false;
}
}
//读取公钥文件内容
public static AsymmetricKeyParameter LoadKey(string KeyPath)
{
try
{
// 读取公钥文件内容//含有"-----BEGIN PUBLIC KEY-----"、"-----END PUBLIC KEY-----"、"\n"等内容
string txtKeyPem = File.ReadAllText(KeyPath);
//SLogText.WriteLog("获取秘钥:txtKeyPem:", txtKeyPem);
// 使用 PemReader 解析公钥
PemReader pemReader = new PemReader(new StringReader(txtKeyPem));
AsymmetricKeyParameter thisKey = (AsymmetricKeyParameter)pemReader.ReadObject();
return thisKey;
}
catch (Exception ex)
{
return null;
}
}
C# .netFramework 微信支付公钥模式验签
最新推荐文章于 2025-03-30 13:23:43 发布