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?
1
votes
You need to find the certificates that key originated. You do not want to store public and private keys in a non trusted located so hackers cannot get both the public and private keys. The key is file in the Program Data folder and you may need admin privilege to open file.
- jdweng
I have the certificate and password that key originated. The root cause of this problem is I import the certificate every time I use it instead of importing it into certificate store. I have changed the way the utility works. Now it doesn't generate new key files anymore.
- Luyin Sun
You are correct. Every time you create a new document a new public key should be generated from the certificate (private key). So you have to import the certificate to get the new public key.
- jdweng
How am I going to import these file? There is no extension. What's the format?
- Luyin Sun
You have the certificate. Why do you want to import the files?
- jdweng
1 Answers
1
votes
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
}
}
}
}