【问题标题】:Private Key Permissions Breaking on Program Exit程序退出时的私钥权限中断
【发布时间】:2017-04-17 14:04:51
【问题描述】:

我有一个小型应用程序作为大型程序的“证书管理器”,这样用户就不必手动安装和配置证书。

这相当简单 - 它有一些证书作为嵌入式资源,它会加载到适当的存储中,然后设置适当的配置权限。

这似乎在程序运行时正常工作。使用 MMC,我可以看到证书已安装。如果我管理私钥,它会正确添加新权限。但是,一旦我关闭证书管理器,权限就会中断。证书仍然安装,但点击管理私钥会弹出类似“密钥不存在”的错误。

另外,如果程序第二次运行,权限将在程序退出后正确“粘”。

这是程序用来验证是否添加了权限的代码。此方法每次都返回“true”,即使之后权限中断。

    private bool GetSecurityStatus(X509Certificate2 cert, X509Store store)
    {
        store.Open(OpenFlags.ReadOnly);

        //add Authenticated Users to private cert
        RSACryptoServiceProvider privKeyRSA = cert.PrivateKey as RSACryptoServiceProvider;
        string keyFilePath = FindKeyLocation(privKeyRSA.CspKeyContainerInfo.UniqueKeyContainerName);
        FileInfo privateKeyFileInfo = new FileInfo(keyFilePath + "\\" + privKeyRSA.CspKeyContainerInfo.UniqueKeyContainerName);
        FileSecurity privateKeyFileSecurity = privateKeyFileInfo.GetAccessControl();

        AuthorizationRuleCollection rules = privateKeyFileSecurity.GetAccessRules(true, true, typeof(NTAccount));
        foreach (FileSystemAccessRule fsar in rules)
        {
            if(fsar.IdentityReference.Value.Contains("Authenticated Users") && fsar.AccessControlType == AccessControlType.Allow && fsar.FileSystemRights == FileSystemRights.FullControl){
                store.Close();return true;
            }
        }
        //Close Private Cert store
        store.Close();
        return false;
    }

FindKeyLocation 返回私钥的 appdata\Microsoft\Crypto\RSA\ 路径。

我认为这与程序退出改变私钥文件本身有关,但我不确定为什么它会在第二次工作。

【问题讨论】:

  • 您似乎根本没有使用商店(除了打开和关闭它),这意味着您正在检查与 cert 关联的私钥的权限,但不一定cert 在证书存储中的表示。
  • @bartonjs 给出的代码只是为了证明权限本身已经找到。
  • 是的,但是如果两个不同的证书实例是独立于 PFX 加载的,它们可能会在使用什么私钥方面存在分歧。所以如果你的检测代码改成读取storevery权限,你可能会发现下面有不同的问题。
  • @bartonjs 我明白了——实际上在不同的区域有直接从商店获取证书的代码,只是没有包含在这个 sn-p 中。谢谢!

标签: c# .net certificate


【解决方案1】:

根据此处的回复,我相信我已经找到了解决问题的方法:

Import certificate with private key programmatically

这里来自 MSDN

https://support.microsoft.com/en-us/help/950090/installing-a-pfx-file-using-x509certificate-from-a-standard-.net-application

我必须在证书的参数中传递两个标志,而不仅仅是 MachineKey

X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    相关资源
    最近更新 更多