Get Private Key from BouncyCastle X509 Certificate? C#

前端 未结 3 1676
北荒
北荒 2021-02-05 15:51

Normally when I grab an X509Certificate2 out of my keystore I can call .PrivateKey to retrieve the cert\'s private key as an AsymmetricAlgorithm<

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-05 16:32

    Don't know BouncyCastle that much but it seems to me that the simple thing to do is to recreate the key based on the key parameters.

    
        public static AsymmetricKeyParameter TransformRSAPrivateKey(AsymmetricAlgorithm privateKey)
        {
            RSACryptoServiceProvider prov = privateKey as RSACryptoServiceProvider;
            RSAParameters parameters = prov.ExportParameters(true);
    
            return new RsaPrivateCrtKeyParameters(
                new BigInteger(1,parameters.Modulus),
                new BigInteger(1,parameters.Exponent),
                new BigInteger(1,parameters.D),
                new BigInteger(1,parameters.P),
                new BigInteger(1,parameters.Q),
                new BigInteger(1,parameters.DP),
                new BigInteger(1,parameters.DQ),
                new BigInteger(1,parameters.InverseQ));
        }
    
    

    You can call the code by using

    
    AsymmetricKeyParameter bouncyCastlePrivateKey = TransformRSAPrivateKey(mycert.PrivateKey);
    
    

    Obviously this assumes that the certificate includes a RSA Key but the same result can be achieved for DSA with DSACryptoServiceProvider and DSAParameters

提交回复
热议问题