Best way to initiate RSACryptoServiceProvider from x509Certificate2?

前端 未结 3 2106
再見小時候
再見小時候 2020-12-14 06:30

What is the best way to initate a new RSACryptoServiceProvider object from an X509Certificate2 I pulled out of a key store? The certificate is asso

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 07:17

    Blowdart's answer is indeed correct. However, for clarity I should point out that if you want your RSACryptoServiceProvider instance to contain both the public and private keys of the X509 certificate (assuming the certificate does have a private key). Check the certificate's HasPrivateKey property.

    RSACryptoServiceProvider rsa;
    if (cert.HasPrivateKey)
        rsa = (RSACryptoServiceProvider)cert.PrivateKey;
    else
        rsa = (RSACryptoServiceProvider)cert.PublicKey.Key;
    

    In the case of RSA when only the public key is present the RSA Parameters will be only Exponent and Modulus, all others will be null; If on the other hand the private key is present the RSA Parameters will contain D, DP, DQ, Exponent, InverseQ, Modulus, P and Q.

提交回复
热议问题