如何使用C#从PKCS#12(.p12)文件获取私钥

我试图使用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为null但如果我使用.pfx certicitae以类似的方式工作。

  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文件中获取私钥?

我有一个类似的问题,我在这里发布,虽然它对你不一样,问题可能也是权限。
我的建议是,首先,您必须确保(我认为您已经这样做)私钥是可导出的,并且您拥有该文件的权限。
接下来,尝试将内容类型导出为X509ContentType.Pkcs12而不是X509ContentType.Pfx
最后,如果可能,为什么不尝试将其导入certstore。 我相信这更安全。 步骤在上面的链接中。

看看这个问题 。 它看起来非常相似。

在文档中 ,它表示.export()不支持Pfx类型,只支持CertSerializedCertPkcs12

这是使用Android完成的 – 所以下面的R.raw.key是我在Android Raw文件夹中的文件。

我打开key.p12作为输入流。 然后我使用库转换为私钥,如示例中所示。

http://www.flexiprovider.de/examples/ExampleSMIMEsign.html

我的代码看起来像这样

 Security.addProvider(new de.flexiprovider.core.FlexiCoreProvider()); // Next, we have to read the private PKCS #12 file, since the the // private key used for signing is contained in this file: DERDecoder dec = new DERDecoder(getResources().openRawResource( R.raw.key)); PFX pfx = new PFX(); try { pfx.decode(dec); SafeBag safeBag = pfx.getAuthSafe().getSafeContents(0) .getSafeBag(0); PKCS8ShroudedKeyBag kBag = (PKCS8ShroudedKeyBag) safeBag .getBagValue(); char[] password = "my password for the p12".toCharArray(); privKey = kBag.getPrivateKey(password); new AsyncLoadStorage(this).execute(); } catch (ASN1Exception e) {