.NET Standard - Merge a certificate and a private key into a .pfx file programmatically

拟墨画扇 提交于 2019-11-29 14:08:11

There's not a way to do this with framework types. It may be possible with BouncyCastle, or other libraries.

.NET Core 2.0 has added the ability to merge a certificate and a key object together (into a new X509Certificate2 object) via extension methods:

X509Certificate2 mergedCert = cert.CopyWithPrivateKey(rsaPrivateKey);
X509Certificate2 mergedCert = cert.CopyWithPrivateKey(dsaPrivateKey);
X509Certificate2 mergedCert = cert.CopyWithPrivateKey(ecdsaPrivateKey);

But that requires compiling specifically for netcoreapp20 (not netstandard20).

The framework types also don't have a way of loading key objects from binary representations (with the exception of CngKey.Import, but that only works on Windows), only from the pre-parsed structures (RSAParameters, DSAParameters, ECParameters).

The easiest way to accomplish this goal on Linux (if BouncyCastle can't help you out) is to use System.Process to spawn a call similar to openssl pkcs12 -export -out tmp.pfx -in tmp.cer -inkey tmp.key -password pass:"".

On Windows you could maybe use CngKey.Import and P/Invoke CertSetCertificateContextProperty (for CERT_NCRYPT_KEY_HANDLE_PROP_ID (78)) to then call cert.Export on the mutated certificate.

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