【问题标题】:How to remove the file created by X509Certificate2.ctor() under AppData\Roaming\Microsoft\Crypto\Keys\?如何删除 AppData\Roaming\Microsoft\Crypto\Keys\ 下 X509Certificate2.ctor() 创建的文件?
【发布时间】:2018-09-05 23:57:11
【问题描述】:
无论何时执行:
new X509Certificate2(bytes)
...在C:\Users\[user]\AppData\Roaming\Microsoft\Crypto\Keys\下创建一个新文件
完成证书后如何删除此文件?
我试过了:
using(new X509Certificate2(bytes)) {...}
没有。
...
cert.Reset();
...
没有。
尝试将字节写入文件并从中读取。
没有。
还有其他建议吗?
【问题讨论】:
标签:
.net
certificate
x509certificate
x509certificate2
【解决方案1】:
如果您没有设置X509KeyStorageFlags.PersistKeySet,那么当您处理(或重置)证书时,或者稍后被垃圾收集时,该文件应该被删除。
如果您确实设置了 X509KeyStorageFlags.PersistKeySet,那么 .NET 将不再自动删除它,您必须手动进行。
try
{
AsymmetricAlgorithm alg = cert.PrivateKey;
if (alg is RSACryptoServiceProvider rsaCsp)
{
rsaCsp.PersistKeyInCsp = false;
rsaCsp.Dispose();
}
else if (alg is DSACryptoServiceProvider dsaCsp)
{
dsaCsp.PersistKeyInCsp = false;
dsaCsp.Dispose();
}
return;
}
catch (CryptographicException)
{
// Maybe not a CAPI key
}
try
{
CngKey cngKey = null;
using (RSA rsa = cert.GetRSAPrivateKey())
using (DSA dsa = cert.GetDSAPrivateKey())
using (ECDsa ecdsa = cert.GetECDsaPrivateKey())
{
if (rsa is RSACng rsaCng)
{
cngKey = rsaCng.Key;
}
else if (dsa is DSACng dsaCng)
{
cngKey = dsaCng.Key;
}
else if (ecdsa is ECDsaCng ecdsaCng)
{
cngKey = ecdsaCng.Key;
}
}
if (cngKey != null)
{
cngKey.Delete();
cngKey = null;
}
}
catch (CryptographicException)
{
}
如果您没有设置 PersistKeySet 但您的进程异常终止,则忘记了应该删除密钥的概念,并且新的 PFX 将创建一个新文件。知道要删除什么很难,而且超出了这个答案的范围。