【发布时间】:2011-07-25 05:02:39
【问题描述】:
我正在尝试使用 PKCS#12 证书对一些数据进行签名,但是我无法从 PKCS#12 (.p12) 文件中获取私钥。
public byte[] sign(string text)
{
string password = "1111";
X509Certificate2 cert = new X509Certificate2("c:\\certificate.p12",password);
byte[] certData = cert.Export(X509ContentType.Pfx,password);
X509Certificate2 newCert = new X509Certificate2(certData, password);
RSACryptoServiceProvider crypt = (RSACryptoServiceProvider)newCert.PrivateKey;
SHA1Managed sha1 = new SHA1Managed();
UnicodeEncoding encoding = new UnicodeEncoding();
byte[] data = encoding.GetBytes(text);
byte[] hash = sha1.ComputeHash(data);
return crypt.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
}
问题是 newCert.PrivateKey 为空,但如果我以类似的方式使用 .pfx 证书,它可以工作。
public byte[] sign(string text)
{
string password = "1234";
X509Certificate2 cert = new X509Certificate2("c:\\certificate.pfx", password);
RSACryptoServiceProvider crypt = (RSACryptoServiceProvider)cert.PrivateKey;
SHA1Managed sha1 = new SHA1Managed();
UnicodeEncoding encoding = new UnicodeEncoding();
byte[] data = encoding.GetBytes(text);
byte[] hash = sha1.ComputeHash(data);
return crypt.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
}
那么问题是如何从 .p12 文件中获取该私钥?
【问题讨论】:
-
您是否为 .PFX 和 .P12 尝试过相同的代码?根据你从哪里得到 P12,我相信它应该是一样的。
标签: c# encryption x509certificate2 pkcs#12