使用Org.BouncyCastle.Crypto从.p12文件获取私钥时出错

时间:2013-05-28 13:07:00

标签: .net cryptography encryption

我使用以下代码在.Net中使用“Org.BouncyCastle.Crypto”获取私钥

        FileStream keyFileStream = File.OpenRead(FileName);
        char[] pwd = Password.ToCharArray();
        Org.BouncyCastle.Pkcs.Pkcs12Store store = new Org.BouncyCastle.Pkcs.Pkcs12Store(keyFileStream, pwd);

        System.Collections.IEnumerator h = store.Aliases.GetEnumerator();
        h.MoveNext();
        object o = h.Current;
        string alias = o.ToString();

        Org.BouncyCastle.Pkcs.AsymmetricKeyEntry privAsymKey = store.GetKey(alias);// as RsaKeyParameters;
        RsaKeyParameters privRSAKey = (RsaKeyParameters)privAsymKey.Key;

但我将“privAsymKey”视为空

我厌倦了Getting private key using OpenSSl的手动方法,我可以获得私钥,这意味着.p12文件是正确的。

任何人都可以帮我修复从.p12文件获取私钥的确切错误的地方

1 个答案:

答案 0 :(得分:1)

经过大量的谷歌搜索后,我发现以下代码可以帮助我使用Org.BouncyCastle.Crypto从.p12文件中获取私钥

//This is the function call
 AsymmetricKeyParameter privateKey = TransformRSAPrivateKey(Certi.PrivateKey);

//这是返回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));