分享vs2008中.net连接java web service服务公钥私钥证书验签的方法
时间:2010-9-10 10:51:43 来源:www.cnblogs.com 作者:交友乐
三、验签
验签的代码是网上找来的,需要注意的是对方可能是公钥加密,我们需要用私钥解密,也可能对方是私钥加密,我们需要公钥解密。我就碰到对方测试环境和生产环境做法不一样,导致花了好几天才找到问题。
/// <summary> ///
引用证书非对称加/解密RSA-私钥验签【OriginalString:原文(有中文用utf-8编码的字节);SignatureString:签名
字符;prikey_path:证书路径;CertificatePW:证书密码;SignType:签名摘要类型(1:MD5,2:SHA1)】
Code [http://www.]
/// </summary> public static bool CerRSAVerifySignatureByPrivate(byte[] OriginalString, byte[] SignatureString, string prikey_path, string CertificatePW, int SignType) { X509Certificate2 x509_Cer1 = new X509Certificate2(prikey_path, CertificatePW); RSACryptoServiceProvider rsapub = (RSACryptoServiceProvider)x509_Cer1.PrivateKey; rsapub.ImportCspBlob(rsapub.ExportCspBlob(false)); RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsapub); byte[] HashData; switch (SignType) { case 1: f.SetHashAlgorithm("MD5");//摘要算法MD5 MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); HashData = md5.ComputeHash(OriginalString); break; default: f.SetHashAlgorithm("SHA1");//摘要算法SHA1 SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider(); HashData = sha.ComputeHash(OriginalString); break; } if (f.VerifySignature(HashData, SignatureString)) { return true; } else { return false; } }
/// <summary> /// 引用证书非对称加/解密RSA-公钥验签【OriginalString:原文(有中文用utf-8编码的字节);SignatureString:签名字符;pubkey_path:证书路径;CertificatePW:证书密码;SignType:签名摘要类型(1:MD5,2:SHA1)】 /// </summary> public static bool CerRSAVerifySignature(byte[] OriginalString, byte[] SignatureString, string pubkey_path, string CertificatePW, int SignType) { X509Certificate2 x509_Cer1 = new X509Certificate2(pubkey_path, CertificatePW); RSACryptoServiceProvider rsapub = (RSACryptoServiceProvider)x509_Cer1.PublicKey.Key; rsapub.ImportCspBlob(rsapub.ExportCspBlob(false)); RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsapub); byte[] HashData; switch (SignType) { case 1: f.SetHashAlgorithm("MD5");//摘要算法MD5 MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); HashData = md5.ComputeHash(OriginalString); break; default: f.SetHashAlgorithm("SHA1");//摘要算法SHA1 SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider(); HashData = sha.ComputeHash(OriginalString); break; } if (f.VerifySignature(HashData, SignatureString)) { return true; } else { return false; }
我是用SHA1算法,注意byte的转换
CerRsa.CerRSAVerifySignature(Encoding.UTF8.GetBytes(orgData.ToString()),
Convert.FromBase64String(payment.Signature), pubkey_path, "", 2)
|