Reputation: 1164
One of utility we created generates too many files in C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys. To safely delete these files I want to open each file and exam the key. How can I open these key files in C#? I looked at code at here. The code only returns public key. Can I get more information form these key files?
Upvotes: 2
Views: 6463
Reputation: 1164
I ended up using following powershell to get a list of valid key from certificate store. I also added c2319c42033a5ca7f44e731bfd3fa2b5 to the list since I am using IIS service. I delete any key file not in this list.
$MachineCertStores = Get-ChildItem Cert:\LocalMachine
$UserCertStores = Get-ChildItem Cert:\CurrentUser
Foreach ($Store in $MachineCertStores)
{
$path = "Cert:\LocalMachine\" + $($store.Name)
$keys = Get-ChildItem $path
Foreach ($Key in $Keys)
{
$UniqueKeyName = $key.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
if ([string]::IsNullOrWhitespace($UniqueKeyName)){
}else{
write-host $UniqueKeyName
$file = Get-Content "validkey.txt"
$containsWord = $file | %{$_ -match $UniqueKeyName.substring(0,32)}
If($containsWord -contains $true)
{
}else{
$UniqueKeyName.substring(0,32) | Out-File 'validkey.txt' -Append
}
}
}
}
Foreach ($Store in $UserCertStores)
{
$path = "Cert:\CurrentUser\" + $($store.Name)
$keys = Get-ChildItem $path
Foreach ($Key in $Keys)
{
$UniqueKeyName = $key.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
if ([string]::IsNullOrWhitespace($UniqueKeyName)){
}else{
write-host $UniqueKeyName
$file = Get-Content "validkey.txt"
$containsWord = $file | %{$_ -match $UniqueKeyName.substring(0,32)}
If($containsWord -contains $true)
{
}else{
$UniqueKeyName.substring(0,32) | Out-File 'validkey.txt' -Append
}
}
}
}
Upvotes: 2