[英]I want to create a p12 file based on a cert file and a key file
证书和密钥文件都是字符串类型。 我尝试使用这个:
RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider();
rsaKey.ImportParameters(keyfile);
X509Certificate2 cert = new X509Certificate2(certfile);
cert.PrivateKey = rsaKey;
cert.Export(X509ContentType.Pkcs12, "xyz");
RestAsynchronicClient client = new RestAsynchronicClient(url, RestDataStandard.JSON, null, cert, logger);
在这里,我在第二行收到转换错误。 从字符串到 RSAParameter 的转换错误。
没有从文件路径或文件内容到RSAParameters
的自动转换; RSACryptoServiceProvider
已过时,不建议用于新代码,并且证书上的PrivateKey
属性在 .NET 的新版本中完全[Obsolete]
。
使用 .NET 5+,这很容易:
byte[] pfxBytes;
using (X509Certificate2 cert = X509Certificate2.CreateFromPemFile(certFile, keyFile))
{
pfxBytes = cert.Export(X509ContentType.Pkcs12, pfxPwd);
}
或者,以更接近您编写的代码的风格:
byte[] pfxBytes;
using (X509Certificate2 cert = new X509Certificate2(certFile))
using (RSA key = RSA.Create())
{
key.ImportFromPem(File.ReadAllText(keyFile));
using (X509Certificate2 certWithKey = cert.CopyWithPrivateKey(key))
{
pfxBytes = certWithKey.Export(X509ContentType.Pkcs12, pfxPwd);
}
}
然后您的参考片段继续忽略 PFX/PKCS12 output 并将证书传递给RestAsynchronicClient
。 由于 Windows 上的一些特性,如果您从这种样式加载证书,这通常不起作用。 但是,如果您将 PFX 加载到新的 X509Certificate2 object 中,那么 state 会略有不同,一切都会很愉快。
RestAsynchronicClient client = new RestAsynchronicClient(
url,
RestDataStandard.JSON,
null,
new X509Certificate2(pfxBytes, pfxPwd),
logger);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.