/// <summary>
/// 使用微信支付平台证书公钥加密验签
/// https://wechatpay-api.gitbook.io/wechatpay-api-v3/qian-ming-zhi-nan-1/qian-ming-yan-zheng
/// </summary>
public class WXPlatform
{
public string PublicKey { get; private set; }
private byte[] _publicKeyBytes { get; set; }
/// <summary>
/// 构造方法
/// </summary>
/// <param name=“publickey”>-----BEGIN CERTIFICATE----- 开头的string,转为bytes->不需要每次都去</param>
public WXPlatform(string publickey)
{
this.PublicKey = publickey;
this._publicKeyBytes = Encoding.UTF8.GetBytes(publickey);
}
/// <summary>
/// 最终提交请求时,需对敏感信息加密,如身份证、银行卡号。
/// 加密算法是RSA,使用从接口下载到的公钥进行加密,非后台下载到的私钥。
/// </summary>
/// <param name=“text”>要加密的明文</param>
/// <param name=“publicKey”> </param>
/// <returns></returns>
public string Encrypt(string text)
{
var x509 = new X509Certificate2(this._publicKeyBytes);
using (var rsa = (RSACryptoServiceProvider)x509.PublicKey.Key)
{
var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(text), true);
return Convert.ToBase64String(buff);
}
}
/// <summary>
/// 验证签名
/// </summary>
/// <param name=“signedString”>私钥加密串-Wechatpay-Signature</param>
/// <param name=“signSourceString”>验签名串-应答时间戳\n应答随机串\n应答报文主体\n</param>
/// <returns></returns>
public bool VerifySign(string signedString, string signSourceString)
{
var x509 = new X509Certificate2(this._publicKeyBytes);
using (var rsa = (RSACryptoServiceProvider)x509.PublicKey.Key)
{
using (var sha256 = new SHA256CryptoServiceProvider())
{
var b = rsa.VerifyData(Encoding.UTF8.GetBytes(signSourceString), sha256, Convert.FromBase64String(signedString));
return b;
}
}
}
}