有一些简单的代码可以使用Spring
将带有私钥的证书导入Windows证书存储区:
.net core 2.2
还有一些简单的代码可以再次读出来:
using (var store = new X509Store(StoreName.Root,StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
store.Close();
}
尽管已将证书成功检索到certCollection中,但即使在先前的 using (var store = new X509Store(StoreName.Root,StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
var certCollection = store.Certificates.Find(X509FindType.FindBySubjectName, commonName, validOnly);
store.Close();
return certCollection;
}
调用中它们不是null和true,它的私钥还是null并且hasPrivateKey是false。为什么会这样?
更新:
Add
答案 0 :(得分:1)
您的密钥被创建为临时密钥,因此当将其添加到持久存储中时,该密钥将被丢弃。
如果要将密钥持久存储在商店证书中,则需要直接将其创建为持久密钥,或者导出到PFX然后重新导入(这是最简单的形式):
// If you're planning on saving to a LocalMachine store you should also | in the
// X509KeyStorageFlags.MachineKeySet bit.
X509KeyStorageFlags storageFlags = X509KeyStorageFlags.PersistKeySet;
X509Certificate2 certWithPersistedKey =
new X509Certificate2(
certWithEphemeralKey.Export(X509ContentType.Pkcs12, ""),
"",
storageFlags);
现在可以像您期望的那样添加certWithPersistedKey
。