从BouncyCastle X509证书获取私钥? C#

时间:2010-07-13 18:28:36

标签: c# x509certificate bouncycastle private-key

通常,当我从密钥库中获取X509Certificate2时,我可以调用.PrivateKeyAsymmetricAlgorithm的形式检索证书的私钥。但是我已经决定使用Bouncy Castle,它的X509Certificate实例只有一个getPublicKey();我看不到从证书中获取私钥的方法。有什么想法吗?

我从Windows-MY密钥库中获取X509Certificate2,然后使用:

//mycert is an X509Certificate2 retrieved from Windows-MY Keystore
X509CertificateParser certParser = new X509CertificateParser();
X509Certificate privateCertBouncy = certParser.ReadCertificate(mycert.GetRawCertData());
AsymmetricKeyParameter pubKey = privateCertBouncy.GetPublicKey();
//how do i now get the private key to make a keypair?

是否有将AsymmetricAlgorithm(C#私钥)转换为AsymmetricKeyParameter(bouncycastle私钥)?

3 个答案:

答案 0 :(得分:21)

Akp = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(this.Certificate.PrivateKey).Private;

答案 1 :(得分:17)

不要太了解BouncyCastle,但在我看来,简单的做法是根据关键参数重新创建密钥。


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

您可以使用

调用代码

AsymmetricKeyParameter bouncyCastlePrivateKey = TransformRSAPrivateKey(mycert.PrivateKey);

显然,这假定证书包含RSA密钥,但对于DSACryptoServiceProviderDSAParameters

的DSA,可以获得相同的结果

答案 2 :(得分:1)

查找.NET X509Certificate2:

X509Certificate2 cert = this.FindCertificate(certificateFriendlyName);

将其解析为BouncyCastle证书并使用X509Certificate2Signature获取签名:

var parser = new X509CertificateParser();
var bouncyCertificate = parser.ReadCertificate(cert.RawData);
var algorithm = DigestAlgorithms.GetDigest(bouncyCertificate.SigAlgOid);
var signature = new X509Certificate2Signature(cert, algorithm);