Is it possible to programmatically generate an X509 certificate using only C#?

前端 未结 2 972
一个人的身影
一个人的身影 2020-11-28 05:14

We\'re trying to generate an X509 certificate (including the private key) programmatically using C# and the BouncyCastle library. We\'ve tried using some of the code from th

相关标签:
2条回答
  • 2020-11-28 05:24

    I realise this is an old post but I found these excellent articles which go through the process:

    Using Bouncy Castle from .NET

    0 讨论(0)
  • 2020-11-28 05:36

    Just to clarify, an X.509 certificate does not contain the private key. The word certificate is sometimes misused to represent the combination of the certificate and the private key, but they are two distinct entities. The whole point of using certificates is to send them more or less openly, without sending the private key, which must be kept secret. An X509Certificate2 object may have a private key associated with it (via its PrivateKey property), but that's only a convenience as part of the design of this class.

    In your first BouncyCastle code example, newCert is really just the certificate and DotNetUtilities.ToX509Certificate(newCert) is built from the certificate only.

    Considering that the PKCS#12 format requires the presence of a private key, I'm quite surprised that the following part even works (considering you're calling it on a certificate which can't possibly know the private key):

    .Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12,
        "password");
    

    (gen.Generate(kp.Private) signs the certificate using the private key, but doesn't put the private key in the certificate, which wouldn't make sense.)

    If you want your method to return both the certificate and the private key you could either:

    • Return an X509Certificate2 object in which you've initialized the PrivateKey property
    • Build a PKCS#12 store and returns its byte[] content (as if it was a file). Step 3 in the link you've sent (mirror) explains how to build a PKCS#12 store.

    Returning the byte[] (DER) structure for the X.509 certificate itself will not contain the private key.

    If your main concern (according to your test case) is to check that the certificate was built from an RSA key-pair, you can check the type of its public key instead.

    0 讨论(0)
提交回复
热议问题