从证书库导入的X509证书没有私钥

X509 certificate imported from certificate store has no private key

有一些简单的代码可以使用 .net core 2.2 将带有私钥的证书导入 Windows 证书存储区:

  using (var store = new X509Store(StoreName.Root,StoreLocation.CurrentUser))
  {
      store.Open(OpenFlags.ReadWrite);
      store.Add(cert);
      store.Close();
  }

还有一些简单的代码可以再次读出来:

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

然而,虽然证书已成功检索到 certCollection 中,但它的私钥为 null 并且 hasPrivateKey 为 false,即使它们在之前的 Add 调用中既不是 null 也不是 true。这是为什么?

更新:

using (RSA rsa = RSA.Create(keySize)) {    
     CertificateRequest certRequest = new CertificateRequest(
         subjectName,
         rsa,
         HashAlgorithmName.SHA512,
         RSASignaturePadding.Pkcs1);

     certRequest.CertificateExtensions
         .Add(newX509SubjectKeyIdentifierExtension(certRequest.PublicKey, false));  
     return certRequest;
}

您的密钥被创建为临时密钥,因此当它被添加到持久存储时,该密钥将被丢弃。

如果您想将密钥持久保存到商店证书中,您需要直接将其创建为持久密钥,或者导出到 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 可以像您期望的那样添加了。