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

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(116)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2017-12-08 kentico7中设置网站的主页
2016-12-08 ChartControl 折线图 柱状图
点击右上角即可分享
微信分享提示