如何在 C# 中使用 Bouncy Castle 导入签名的 SSL 证书 (Mono/Xamarin)?

How to import a signed SSL certificate using Bouncy Castle in C# (Mono/Xamarin)?

我使用 Bouncy Castle 生成私钥以及 PKCS10 CSR,然后将其发送到远程服务器进行签名。我以字符串形式返回标准的 base64 编码签名 SSL 证书作为响应。问题是,如何从字符串导入签名证书,然后将私钥和签名证书都保存为 PKCS12 (.PFX) 文件?

此外,如何捆绑 CA 证书以包含在 PFX 文件中?

// Generate the private/public keypair
RsaKeyPairGenerator kpgen = new RsaKeyPairGenerator ();
CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator ();
kpgen.Init (new KeyGenerationParameters (new SecureRandom (randomGenerator), 2048));
AsymmetricCipherKeyPair keyPair = kpgen.GenerateKeyPair ();

// Generate the CSR
X509Name subjectName = new X509Name ("CN=domain.com/name=Name");
Pkcs10CertificationRequest kpGen = new Pkcs10CertificationRequest ("SHA256withRSA", subjectName, keyPair.Public, null, keyPair.Private);
string certCsr = Convert.ToBase64String (kpGen.GetDerEncoded ());

// ** certCsr is now sent to be signed  **
// ** let's assume that we get "certSigned" in response, and also have the CA **
string certSigned = "[standard signed certificate goes here]";
string certCA = "[standard CA certificate goes here]";

// Now how do I import certSigned and certCA
// Finally how do I export everything as a PFX file?

Bouncy Castle 是一个非常强大的库,但是缺少文档使得它很难使用。在所有 类 和方法中搜索了太久之后,我终于找到了我要找的东西。以下代码将获取之前生成的私钥,将其与签名证书和 CA 捆绑在一起,然后将其保存为 .PFX 文件:

// Import the signed certificate
X509Certificate signedX509Cert = new X509CertificateParser ().ReadCertificate (Encoding.UTF8.GetBytes (certSigned));
X509CertificateEntry certEntry = new X509CertificateEntry (signedX509Cert);

// Import the CA certificate
X509Certificate signedX509CaCert = new X509CertificateParser ().ReadCertificate (Encoding.UTF8.GetBytes (certCA ));
X509CertificateEntry certCaEntry = new X509CertificateEntry (signedX509CaCert);

// Prepare the pkcs12 certificate store
Pkcs12Store store = new Pkcs12StoreBuilder ().Build ();

// Bundle together the private key, signed certificate and CA
store.SetKeyEntry (signedX509Cert.SubjectDN.ToString () + "_key", new AsymmetricKeyEntry (keyPair.Private), new X509CertificateEntry[] {
    certEntry,
    certCaEntry
});

// Finally save the bundle as a PFX file
using (var filestream = new FileStream (@"CertBundle.pfx", FileMode.Create, FileAccess.ReadWrite)) {
    store.Save (filestream, "password".ToCharArray (), new SecureRandom ());
}

欢迎反馈和改进!