How to check if an RSA key container exists in .NET.

We have

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

How can I make sure that a new key is not created if the key with ContainerName does not exist?

+6
source share
3 answers

Try the following:

  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; } 
+6
source

Here the powershell script parameter is used to check the name of this container:

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

If you really need to list the keys installed on the system, you can take the code from KeyPal at http://www.jensign.com/KeyPal/index.html

+4
source

you can use

 .PersistKeyInCsp = false 

Your cryptographic provider who ensures that the key does not remain in the container. Is that what you mean?

+1
source

Source: https://habr.com/ru/post/887933/


All Articles