尝试使用以下代码从X509Certificate2
获取X509Store
对象时:
private X509Certificate2 GetKey()
{
try
{
X509Store store = new X509Store("WebHosting", StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var collection = store.Certificates.Find(X509FindType.FindBySubjectName, "xxxxxxx", true);
if (collection.Count == 0)
{
throw new Exception("No keys matched");
}
if (collection.Count > 1)
{
StringBuilder sb = new StringBuilder();
sb.Append("More than 1 key matched:\r\n");
foreach (var cert in collection)
{
sb.Append($"{cert.SubjectName} - {cert.Thumbprint}\r\n");
}
throw new Exception(sb.ToString());
}
return collection[0];
}
catch (Exception ex)
{
// something really bad happened, log it
Logger.LogException(ex);
throw;
}
}
我成功获得了密钥;但是,当尝试使用key.PrivateKey
在对象中获取私钥时,我收到以下错误:OpenCSP failed with error code 2148073494.
查找Windows错误2148073494,我得到nte_bad_keyset
。看起来在其他情况下出现了同样错误here的错误,但他们将该错误关闭为已解决。当我在控制台应用程序中运行这段代码时,它工作正常,它也可以在我在IISExpress下运行的测试环境中正常工作。在IIS下的生产环境中运行时,每次都会出现此错误。我尝试在管理员用户的上下文中运行,以确保它不是一个奇怪的权限错误,同样的事情。根据我对这个Windows错误的理解,是Windows给了我密钥所在的位置,然后告诉我该地址没有任何内容。我正在使用"System.Security.Cryptography.Algorithms": "4.3.0"
。
编辑:我应该注意到,作为测试的一部分,我实际上从生产环境中获取了我正在寻找的确切证书到我的测试环境中并且它加载得很好。我还在生产环境中运行控制台应用程序,拉动相同的密钥,它运行正常。
答案 0 :(得分:0)
最终,答案是“在将私钥导入证书存储区后删除了私钥”(或者,也许有可能会混淆Windows以记住密钥存在的位置,尽管它实际上并没有存在)。
如果您知道它,例如,工作一段时间然后停止:
> certutil -store my
...
================ Certificate 6 ================
Serial Number: 3451b93c10f9279348a949f729d1ff10
Issuer: CN=localhost
NotBefore: 1/26/2015 2:19 PM
NotAfter: 1/25/2020 4:00 PM
Subject: CN=localhost
Signature matches Public Key
Root Certificate: Subject matches Issuer
Template:
Cert Hash(sha1): 15 e3 4c d3 2d a7 54 99 a9 17 8f 17 26 25 63 25 8f 3a 94 28
Key Container = IIS Express Development Certificate Container
Unique container name: fad662b360941f26a1193357aab3c12d_1fcb2e07-cec4-4ba1-9c78-58a431e1aefd
Provider = Microsoft RSA SChannel Cryptographic Provider
Encryption test passed
CertUtil: -store command completed successfully.
看到它位于“Microsoft RSA SChannel加密提供程序”中,转到https://msdn.microsoft.com/en-us/library/windows/desktop/bb204778(v=vs.85).aspx并看到密钥文件位于%ALLUSERSPROFILE%\Application Data\Microsoft\Crypto\RSA\MachineKeys
。 Unique container name
恰好是它所拥有的文件的名称。
因此,打开该目录,右键单击该文件。
稍后,在您开始获取密钥集错误后,在安全日志中搜索文件删除审核(来自安全审核的事件4663):
An attempt was made to access an object.
Subject:
Security ID: SOMEDOMAIN\theaccount
Account Name: theaccount
Account Domain: SOMEDOMAIN
Logon ID: 0xabcdef
Object:
Object Server: Security
Object Type: File
Object Name: C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys\fad662b360941f26a1193357aab3c12d_1fcb2e07-cec4-4ba1-9c78-58a431e1aefd
Handle ID: 0xef8
Process Information:
Process ID: 0xf54
Process Name: C:\Windows\explorer.exe
Access Request Information:
Accesses: DELETE
Access Mask: 0x10000
这将告诉你什么进程/用户执行了删除操作...也许这足以确定出现了什么问题。
您可能会以编程方式更多地进行私钥文件识别和审核注册;但这是我知道解释它的最快方式。