将私钥添加到X509证书 [英] Add Private Key to X509Certificate

查看:49
本文介绍了将私钥添加到X509证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些当前使用OpenSSL.net为证书签名请求创建公用/专用密钥对的代码.该请求配有公钥,并发送到CA,CA会返回已签名的证书.然后将先前创建的私钥添加到证书中:

I'm working on some code that currently uses OpenSSL.net to create a public/private key pair for a Certificate Signing Request. The request is equipped with the public key and sent to a CA which returns a signed certificate. Then the previously created private key is added to the certificate:

myCert.PrivateKey = CryptoKey.FromPrivateKey(rsa.PrivateKeyAsPEM, null);

问题是我需要一个.net X509证书,因为该软件的其余部分对TLS使用SslStream和其他.net类.

The problem is I need a .net X509Certificate because the rest of the software uses SslStream and other .net classes for TLS.

我能够从CA的响应中创建一个证书,但是没有找到向其添加私钥的方法.我还尝试从CA的响应中创建OpenSSL证书,将其导出为DER或PEM并从中创建.net证书,但它始终会忽略私钥.

I was able to create a certificate from the CA's response, but I did not find a way to add the private key to it. I also tried creating an OpenSSL certificate from the CA's response, exporting that as DER or PEM and creating the .net certificate from that, but it always ignores the private key.

关于如何解决此问题的任何想法?

Any ideas on how I could solve this problem?

推荐答案

我创建了一个小的辅助程序NuGet包,以基于公钥创建 X509证书,并私有(RSA)密钥.

I've created a small helper NuGet package to create a X509 certificate based on public key and private (rsa) key.

// Generate with: openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout private.key -out certificate_pub.crt
string certificateText = File.ReadAllText("certificate_pub.crt");
string privateKeyText = File.ReadAllText("private.key");

ICertificateProvider provider = new CertificateFromFileProvider(certificateText, privateKeyText);
X509Certificate2 certificate = provider.Certificate;

// Example: use the PrivateKey from the certificate above for signing a JWT token using Jose.Jwt:
string token = Jose.JWT.Encode(payload, certificate.PrivateKey, JwsAlgorithm.RS256);

请参见 NuGet

See NuGet and Github-project for functionality and code-examples based on opensslkey.

这篇关于将私钥添加到X509证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆