将私钥导出为字节数组的最佳方法

发布于 2024-12-11 10:47:32 字数 263 浏览 0 评论 0原文

我编写的应用程序必须从用户那里获取私钥,然后将其作为 base64 发送到另一个应用程序,我想允许用户插入带有私钥的 X509Certificate2。 现在我的大问题是如何将私钥从 AsimetricAlgorithm 对象转换为包含所有私钥的 bate 数组? 我看到我可以使用 openSSl - 将所有证书转换为 pem 文件,然后转换为 RSA 文件 - 并读取私钥,但我不想使用它,因为:我不想在文件、3P 库上使用,它不是安全等等.. 有谁知道另一种方法可以做到这一点?

提前致谢!

I write application that has to get private key from the user and then send it to another application as base64, I want to allow the user to insert a X509Certificate2 with the private key.
Now my bigproblem is how can I convert the private key from AsimetricAlgorithm object to bate array that contains all the private key?
I saw that I can use openSSl - convert all the certificate to pem file, and then to RSA file - and read the private key, but I dont want to use it because: I dont want to use on files, 3P library, it's not secure and so on..
does anyone know about another way to do that?

thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回首观望 2024-12-18 10:47:32

您从 X509Certificate2PrivateKey 属性获取的 AmetryAlgorithm 对象实际上是从 派生的各种类型之一的实例非对称算法,例如RSACryptoServiceProviderDSACryptoServiceProvider等...

您需要确定私钥的类型你正在处理,并适当地施放它。转换后,您应该能够调用 ExportCspBlob(true) 来获取私钥数据。

示例(假设有 RSA 密钥):

public string GetRSAPrivateKeyBase64(X509Certificate2 certificate)
{
    var privateKey = certificate.PrivateKey as RSACryptoServiceProvider;
    if (privateKey == null) throw new Exception("Not an RSA private key");
    // Export the CSP blob, including private key parameters 
    var cspBlob = privateKey.ExportCspBlob(true);
    return Convert.ToBase64String(cspBlob);
}

The AsymmetricAlgorithm object you get from the PrivateKey property of your X509Certificate2 will in fact be an instance of one of the various types derived from AsymmetricAlgorithm, such as RSACryptoServiceProvider, DSACryptoServiceProvider, etc...

You will need to determine the type of private key you're dealing with, and cast it appropriately. Once cast, you should be able to call ExportCspBlob(true) to get the private key data.

Example (assuming an RSA key):

public string GetRSAPrivateKeyBase64(X509Certificate2 certificate)
{
    var privateKey = certificate.PrivateKey as RSACryptoServiceProvider;
    if (privateKey == null) throw new Exception("Not an RSA private key");
    // Export the CSP blob, including private key parameters 
    var cspBlob = privateKey.ExportCspBlob(true);
    return Convert.ToBase64String(cspBlob);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文