中行P1签名及验签

分享中国银行快捷.NET P1签名和验签方法代码中ReturnValue为自定义类型请无视

#region 验证签名
/// <summary>
/// 验证签名
/// </summary>
/// <param name="plainText">返回数据原文</param>
/// <param name="pubKeyPath">公钥证书地址</param>
/// <param name="signatureData">签名值</param>
/// <returns></returns>
public static bool VerifyBankGatewayShortPaySign(string plainText, string pubKeyPath, string signatureData)
{
bool bVerify;
try
{
//将base64签名数据转码为字节
byte[] signedBase64 = Convert.FromBase64String(signatureData);
byte[] orgin = Encoding.UTF8.GetBytes(plainText);
//加载公钥
X509Certificate2 x509_Cer1 = new X509Certificate2(pubKeyPath);

using (RSACryptoServiceProvider oRSA = new RSACryptoServiceProvider())
{
oRSA.FromXmlString(x509_Cer1.PublicKey.Key.ToXmlString(false));

bVerify = oRSA.VerifyData(orgin, "SHA1", signedBase64);
return bVerify;
}
}
catch (Exception ex)
{
return false;
}
}
#endregion


/// <summary>
/// 证书
/// </summary>
/// <param name="certifyFilePath">证书路径</param>
/// <param name="certifyPassWord">证书密码</param>
/// <returns></returns>
private static X509Certificate2 RetrieveX509Certificate(string certifyFilePath, string certifyPassWord)
{
if (string.IsNullOrEmpty(certifyPassWord))

return new X509Certificate2(certifyFilePath);
else
return new X509Certificate2(certifyFilePath, certifyPassWord);
}


#region 创建签名
/// <summary>
/// 根据原文创建P1签名
/// </summary>
/// <param name="plainText">请求数据原文</param>
/// <param name="prikeyPath">私钥证书地址</param>
/// <param name="pfxPwd">私钥密码</param>
/// <returns></returns>
public static string CreateBankGatewayShortPaySign(string plainText, string prikeyPath, string pfxPwd)
{
string sign;
try
{
byte[] plainByte = System.Text.Encoding.UTF8.GetBytes(plainText);
//加载私钥
X509Certificate2 myCert = RetrieveX509Certificate(prikeyPath, pfxPwd);
using (RSACryptoServiceProvider RSA = (RSACryptoServiceProvider)myCert.PrivateKey)
{
RSAPKCS1SignatureFormatter rsaDeformatter = new RSAPKCS1SignatureFormatter(RSA);
rsaDeformatter.SetHashAlgorithm("SHA1");
SHA1Managed sha = new SHA1Managed();
byte[] byteHash = sha.ComputeHash(plainByte);
//执行签名
byte[] encryptedSignatureData = rsaDeformatter.CreateSignature(byteHash);
sign = Convert.ToBase64String(encryptedSignatureData);

}
return sign;
}
catch (Exception ex)
{
return "";
}

}
#endregion

分享不易使用请关注点赞谢谢

posted @ 2016-04-22 11:19  心灬无痕  阅读(622)  评论(0编辑  收藏  举报