Add Private Key to X509Certificate

荒凉一梦 提交于 2019-12-05 17:26:59

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

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

I guess maybe you are missing some conceptual ideas here?

A Certificate is not supposed to contain a Private Key. The Private Key is always private, a certificate is what that binds your public key to your distinguished name. In other words a Certificate is a document that is signed by an authority that confirms that a particular Public Key, that you share with the world, belongs to you and no one else. Therefore it never can contain the Private Key, because you share your certificate with the world!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!