我在使用 FromXmlString
方法从 XML 加载 X509Certificate2
时遇到困难。我遇到的异常是 m_safeCertContext is an invalid handle.
System.Security.Cryptography.CryptographicException occurred
HResult=-2146233296
Message=m_safeCertContext is an invalid handle.
Source=System
StackTrace:
at System.Security.Cryptography.X509Certificates.X509Certificate2.get_HasPrivateKey()
at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
...
为了创建 XML,我正在加载 .pfx
文件并使用 ToXmlString
;
var certificate = new X509Certificate2(
@"D:\public_privatekey.pfx",
(string)null,
X509KeyStorageFlags.Exportable
);
var exportedPrivate = certificate.PrivateKey.ToXmlString(true);
这会生成这样开头的 XML...
<RSAKeyValue><Modulus>y0iuejYHYajI...
要重新创建证书,我正在使用...
var certificate = new X509Certificate2();
certificate.PrivateKey.FromXmlString(xml);
其中 xml
是包含 XML 内容的字符串。
FromXmlString
调用引发异常。
我刚开始使用证书,但我最好的猜测是 .pfx
包含公钥和私钥,可能还有一些其他重要数据,我需要所有这些才能按顺序使用拥有有效的 X509 证书。
但是我无法直接在 X509Certificate2
上找到 ToXmlString
和 FromXmlString
。我应该怎么做?感谢您的任何建议。
最佳答案
X.509 证书以称为 ASN.1/DER 编码的结构化二进制格式描述。 ASN.1是一种描述证书内容的语言,DER是符合ASN.1结构的内容编码。
可以使用 Export
将内存中的证书与私钥分开编码。使用内容类型 X509ContentType.Cert
的方法。您还可以通过指定 Pfx
或 Pkcs12
将证书和私钥导出回“pfx”。如果您需要 XML,则可以使用 base 64 对字节数组结果进行编码。然后可以将其存储到 XML CDATA 元素中。
通常私钥也以二进制 PKCS#8 容器格式存储,也使用 ASN.1/DER 定义。然而,Microsoft 选择默认将 key 存储为 Microsoft 专有的 XML 格式。
关于c# - 在数据库中存储和检索私钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45290582/