如何检查.NET中是否存在RSA密钥容器

时间:2011-05-12 14:24:03

标签: .net encryption cryptography

我们有

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

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

3 个答案:

答案 0 :(得分:7)

试试这个:

    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;
    }

答案 1 :(得分:4)

这是我们用来测试给定容器名称的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/KeyPal/index.html

借用KeyPal中的代码

答案 2 :(得分:1)

您可以使用

.PersistKeyInCsp = false

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