【问题标题】:How to check if RSA key container exists in .NET如何检查 .NET 中是否存在 RSA 密钥容器
【发布时间】:2011-05-12 14:24:02
【问题描述】:

我们有

    Dim cp As New CspParameters()
    cp.KeyContainerName = ContainerName
    cp.Flags = CspProviderFlags.UseMachineKeyStore

如果带有 ContainerName 的密钥不存在,如何确保不创建新密钥?

【问题讨论】:

    标签: .net encryption cryptography


    【解决方案1】:

    试试这个:

        public static bool DoesKeyExists(string containerName)
        {
            var cspParams = new CspParameters
            {
                Flags = CspProviderFlags.UseExistingKey,
                KeyContainerName = containerName
            };
    
            try
            {
                var provider = new RSACryptoServiceProvider(cspParams);
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }
    

    【讨论】:

    • 这不是很好,因为它假定一般异常意味着它不存在,这不是好的做法。但是,据我所知,这似乎是唯一的方法。
    • 将标志切换为 Flags = CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore 为我工作。
    【解决方案2】:

    这是我们用来测试给定容器名称的 powershell 脚本:

    # Test if an rsa key container exists on this system.
    function Test-RsaKeyContainerName(
        [Parameter(Mandatory=$true)][string] $ContainerName,
        [Parameter(Mandatory=$false)][switch] $UserContainer = $false
    ) {
        $csp = New-Object -TypeName "System.Security.Cryptography.CspParameters";
        $csp.KeyContainerName = $ContainerName;
        if (!($UserContainer)) {
            $csp.Flags = [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore;
        }
        $csp.Flags = $csp.Flags -bor [System.Security.Cryptography.CspProviderFlags]::UseExistingKey;
        try {
            $rsa = New-Object -TypeName "System.Security.Cryptography.RSACryptoServiceProvider" -ArgumentList ($csp);
        } catch [System.Management.Automation.MethodInvocationException] {
            if ($error[0].Exception.InnerException -ne $null -and
                $error[0].Exception.InnerException.GetType() -eq [System.Security.Cryptography.CryptographicException] -and
                $error[0].Exception.InnerException.Message.StartsWith("Keyset does not exist")) {           
                return $false;
            } else {
                throw;
            }       
        }
        return $true;
    }
    

    如果你确实需要枚举系统上安装的密钥,可以在http://www.jensign.com/dotnet/keypal/source/KeyPal.txtKeyPal借用代码

    【讨论】:

    • 由于 jensign 页面已经消失,您可以使用 repo 链接更新吗?
    • 更新了 jensign.com 的断开链接
    【解决方案3】:

    你可以使用

    .PersistKeyInCsp = false
    

    在您的加密提供商上,这将确保密钥不会留在容器中。这是你的意思吗?

    【讨论】:

    • 不是一个好主意,如果密钥在进程开始之前就存在,它将被删除。
    猜你喜欢
    • 2013-07-12
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    • 2013-07-03
    • 2011-01-17
    • 2020-08-19
    • 1970-01-01
    相关资源
    最近更新 更多