我们有
Dim cp As New CspParameters()
cp.KeyContainerName = ContainerName
cp.Flags = CspProviderFlags.UseMachineKeyStore
如果ContainerName的密钥不存在,如何确保不创建新密钥?
答案 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
在您的加密提供程序上,它将确保密钥不会遗留在容器中。这是你的意思吗?