HttpWebRequest client authentication with cert and key in pem format
HttpWebRequest client authentication
回答1
You need to convert your private key and pem certificate into #pkcs12 form:
openssl pkcs12 -inkey private.key -in client_certificate.pem -export -out client_certificate.p12
After this, you can specify this p12 file in your C# code:
rq.ClientCertificates.Add(X509Certificate.CreateFromCertFile("c:\\client_certificate.p12"));
https://blog.csdn.net/CAI____NIAO/article/details/104367507
最近项目中需要通过https对接客户的服务器API,客户给的格式为.pem和.key的证书和私钥文件,然后我没有找到C#通过证书和密钥两个文件创建证书的方法,要通过X509Certificate2创建证书只能是引入一个文件,最后找到方法如下:
X509Certificate2类创建证书文件必须使用同时包含证书、公钥、私钥的证书文件格式;
客户给的.pem和.key文件,必须转化格式才可以直接使用。
.pem包含公钥和证书,.key包含私钥,需要通过OpenSSL将其转化成同时包含证书、公钥、私钥的证书文件格式。
转换方法:
打开OpenSSL,输入pkcs12 -export -out D:/client.pfx -inkey D:/client.key -in D:/client.pem,
会提示输出两次密码,此密码为生成的.pfx格式证书文件的密码;
https://stackoverflow.com/a/5394967/13338936
With respect to easily importing the RSA private key, without using 3rd party code such as BouncyCastle, I think the answer is "No, not with a PEM of the private key alone."
However, as alluded to above by Simone, you can simply combine the PEM of the private key (*.key) and the certificate file using that key (*.crt) into a *.pfx file which can then be easily imported.
To generate the PFX file from the command line:
openssl pkcs12 -in a.crt -inkey a.key -export -out a.pfx
Then use normally with the .NET certificate class such as:
using System.Security.Cryptography.X509Certificates;
X509Certificate2 combinedCertificate = new X509Certificate2(@"C:\path\to\file.pfx");
Now you can follow the example from MSDN for encrypting and decrypting via RSACryptoServiceProvider:
I left out that for decrypting you would need to import using the PFX password and the Exportable flag. (see: BouncyCastle RSAPrivateKey to .NET RSAPrivateKey)
X509KeyStorageFlags flags = X509KeyStorageFlags.Exportable;
X509Certificate2 cert = new X509Certificate2("my.pfx", "somepass", flags);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;
RSAParameters rsaParam = rsa.ExportParameters(true);