.net - 提取C#中的私钥字节

标签 .net openssl

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

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

openssl.exe rsa -in privateKey.pem -out private.pem

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

我想使用.NET库或Bouncy CaSTLe库在C#中执行相同的操作。

我该怎么做呢?

最佳答案

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

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

关于.net - 提取C#中的私钥字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6258771/

相关文章:

由于猴子补丁的能力,.NET 4 可以实现更好的单元测试/模拟?

php - 如何让 SSL 在 fsockopen 中工作?

nginx - CentOS 安装 nginx 失败

openssl - mysql2:库未加载:自制软件更新后的/usr/local/opt/openssl/lib/libssl.1.0.0.dylib

c# - AutoMapper 2.1.265 中缺少成员

c# - 是否有可能使 WinForms 选项卡控件能够像 IE 或 Firefox 一样进行选项卡重新排序?

encryption - 连续的 OpenSSL PKCS12 生成产生不同的私钥内容

c - Openssl 中的 ECB、CFB、OFB 密码模式

c# - 我需要帮助在 C# 中使用 <string, char> 格式的字典

.net - 将配置信息放入DLL