与关联在.net中的X509Certificate2类的私有密钥密钥、net

2023-09-03 03:40:35 作者:笑若扶风

我工作的一些code,创建一个x509证书和公钥/私钥对。公钥添加到证书,它被发送到CA其中签署它

I'm working on some code that creates a X509certificate and a public/private key pair. The public key is added to the certificate and it is sent to an CA which signs it.

返回的证书,然后通过System.Security.Cryptography.X509Certificates.X509Certificate2类访问。现在,我想用这个证书来启动与其他客户端的安全连接。所以我用的是SslStream类。要启动SSL握手我用这个方法:

The returned certificate is then accessed through the System.Security.Cryptography.X509Certificates.X509Certificate2 class. Now I want to use this certificate to initiate a secure connection with other clients. Therefore I use the SslStream class. To start the SSL Handshake I use this method:

server.AssociatedSslStream.AuthenticateAsServer(
                        MyCertificate,                      // Client Certificate
                        true,                               // Require Certificate from connecting Peer
                        SslProtocols.Tls,                   // Use TLS 1.0
                        false                               // check Certificate revocation
                    );

这个方法要求私钥与证书相关联。当然由CA返回的证书不包含专用密钥。但它存储为在硬盘.key文件。该X509Certificate2类有一个名为PrivateKey属性,我想将证书的私钥相关联,但我无法找到一个方法来设置该属性。

This method requires that the private key is associated with the certificate. Of course the certificate returned by the CA does not contain a private key. But it is stored as .key file on the harddrive. The X509Certificate2 class has a property called PrivateKey which I guess will associate a private key with the certificate, but I can't find a way to set this property.

有没有什么办法可以与.NET X509类私钥相关联?

Is there any way I can associate the private key with the .net X509 class?

推荐答案

对于其他人同样的问题,我发现一个整洁的小片code,它可以让你做到这些:

For everyone else with the same problem, I found a neat little piece of code that let's you do exactly that:

HTTP://www.$c$ cproject.com/Articles/162194/Certificates-to-DB-and-Back

byte[] certBuffer = Helpers.GetBytesFromPEM(publicCert, PemStringType.Certificate);
byte[] keyBuffer  = Helpers.GetBytesFromPEM(privateKey, PemStringType.RsaPrivateKey);

X509Certificate2 certificate = new X509Certificate2(certBuffer, password);

RSACryptoServiceProvider prov = Crypto.DecodeRsaPrivateKey(keyBuffer);
certificate.PrivateKey = prov;
 
精彩推荐
图片推荐