在C#中提取私钥字节

Sub*_*bbu 3 .net openssl

我目前能够使用以下命令使用OpenSSL从PFX文件中提取私钥:

openssl pkcs12 -in filename.pfx -nocerts -out privateKey.pem

openssl.exe rsa -in privateKey.pem -out private.pem
Run Code Online (Sandbox Code Playgroud)

private.pem文件以... ---BEGIN RSA PRIVATE KEY---结尾---END RSA PRIVATE KEY---

我想在C#中使用.NET库或Bouncy Castle库来做同样的事情.

我该怎么做呢?

And*_*ykh 5

这对我有用。也应该为您工作:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;

namespace SO6258771
{
    class Program
    {
        static void Main()
        {
            // Load your certificate from file
            X509Certificate2 certificate = new X509Certificate2("filename.pfx", "password", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

            // Now you have your private key in binary form as you wanted
            // You can use rsa.ExportParameters() or rsa.ExportCspBlob() to get you bytes
            // depending on format you need them in
            RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificate.PrivateKey;

            // Just for lulz, let's write out the PEM representation of the private key
            // using Bouncy Castle, so that we are 100% sure that the result is exaclty the same as:
            // openssl pkcs12 -in filename.pfx -nocerts -out privateKey.pem
            // openssl.exe rsa -in privateKey.pem -out private.pem

            // You should of course dispose of / close the streams properly. I'm skipping this part for brevity
            MemoryStream memoryStream = new MemoryStream();
            TextWriter streamWriter = new StreamWriter(memoryStream);
            PemWriter pemWriter = new PemWriter(streamWriter);

            AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(rsa);
            pemWriter.WriteObject(keyPair.Private);
            streamWriter.Flush();

            // Here is the output with ---BEGIN RSA PRIVATE KEY---
            // that should be exactly the same as in private.pem
            Console.Write(Encoding.ASCII.GetString(memoryStream.GetBuffer()));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 至关重要的是,要包含RsaPrivateCrtKeyParameters,而不要包含Org.BouncyCastle.Utilities.IO.Pem。这就是为什么@Subbu在编译过程中具有无效参数的原因。 (3认同)

Sub*_*bbu 5

我发现PEMwriter仅适用于VS2005中的.NET 2.0..NET 3.5 SDK环境强调pemWriter.WriteObject(keyPair.Private);由于转换问题导致的错误.如果您尝试将其转换为PEMObjectGenerator并最终构建并调试代码,则在调试器到达此行代码时会引发InvalidCastException.我也将在充气城堡论坛中宣传这一点.

  • 我对此表示反对.它适用于.NET 3.5和.NET 2.0.由于使用了我添加的命名空间,因此出现了强制转换问题. (2认同)
  • 您可以将此编辑到您的问题中,而不是将其作为答案/评论吗?谢谢. (2认同)
  • @Bill:当我读到它时,这是一个答案 - 它恰好是坏消息. (2认同)
  • 我同意@John ......尽管有各种旗帜,但这听起来像一个完全有效的自我回答. (2认同)