จะนำเข้าใบรับรอง SSL ที่ลงนามโดยใช้ Bouncy Castle ใน C # (Mono / Xamarin) ได้อย่างไร

ฉันใช้ Bouncy Castle เพื่อสร้างคีย์ส่วนตัว รวมถึง PKCS10 CSR ซึ่งฉันจะส่งไปยังเซิร์ฟเวอร์ระยะไกลเพื่อลงนาม ฉันได้รับใบรับรอง SSL ที่เข้ารหัส base64 มาตรฐานที่ลงนามแล้วกลับมาโดยตอบสนองเป็นสตริง คำถามคือ ฉันจะนำเข้าใบรับรองที่ลงนามจากสตริงได้อย่างไร แล้วบันทึกทั้งคีย์ส่วนตัวและใบรับรองที่ลงนามเป็นไฟล์ 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?

person Stigz    schedule 24.01.2015    source แหล่งที่มา


คำตอบ (1)


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 ());
}

ข้อเสนอแนะและการปรับปรุงยินดีต้อนรับ!

person Stigz    schedule 28.01.2015
comment
แต่คุณจำเป็นต้องมีใบรับรอง CA หรือใบรับรองระดับกลางใดๆ เพื่อดึงสิ่งนี้ออก - person Richard Barker; 29.03.2016