ris*_*ism 5 c# certificate x509certificate2 .net-core
有一些简单的代码可以使用以下命令将带有私钥的证书导入到 Windows 证书存储中.net core 2.2:
using (var store = new X509Store(StoreName.Root,StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
store.Close();
}
Run Code Online (Sandbox Code Playgroud)
还有一些同样简单的代码可以再次将其读出来:
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;
}
Run Code Online (Sandbox Code Playgroud)
然而,尽管证书已成功检索到 certCollection 中,但它的私钥为 null 并且 hasPrivateKey 为 false,即使它们在之前的调用中不为 null 且为 true Add。为什么是这样?
更新:
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;
}
Run Code Online (Sandbox Code Playgroud)
您的密钥被创建为临时密钥,因此当将其添加到持久存储时,该密钥将被丢弃。
If you want to persist the key into the store certificate, you either need to create it as a persisted key directly, or export to a PFX then re-import (which is the easiest form):
// 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);
Run Code Online (Sandbox Code Playgroud)
Now certWithPersistedKey can be added like you expect.
| 归档时间: |
|
| 查看次数: |
4334 次 |
| 最近记录: |