iisrsax509certificate2

Clean my MachineKeys folder by removing multiple RSA files without touching IIS ones


I'm currently running IIS on my server using an app instantiating certificates.

By doing this code, for instance :

X509Certificate2 myX509Certificate = new 
X509Certificate2(Convert.FromBase64String(byteArrayRawCertificate), passwordCertificate, 
X509KeyStorageFlags.Exportable | 
X509KeyStorageFlags.MachineKeySet | 
X509KeyStorageFlags.PersistKeySet);

The code works fine. But I encounter a problem on my computer, on the following folder :

C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys

3KB RSA files keep on being added on that folder. For now, I have more than a million files like those ones :

enter image description here

I would like to delete those files, but :

Thanks in advance for your help.


Solution

  • We ended up with this same problem.... 42 GB of machine key files. So I wrote this powershell: RemoveMachineKeys.ps1. Took a while before it actually started deleting them, but once it did the script blazed through them pretty fast. I added protection from removing IIS machine keys.

    I could not use the above answers that depended upon which user created the keys, as these keys were being created in a web site and had the same created by user. I also did not want to care about the application pool name if I did not have to.

    Here is the raw script:

    #Requires -RunAsAdministrator
    Clear-Host
    
    $deleteDate = (Get-Date).AddMonths(-2)
    $counter = 0
    
    # https://port135.com/remove-older-files-machinekeys/
    # Back up the three files below. These files are used by IIS. It’s important to back them up before removing any files from MachinkeKeys folder.
    # 
    # 6de9cb26d2b98c01ec4e9e8b34824aa2_GUID iisConfigurationKey
    # d6d986f09a1ee04e24c949879fdb506c_GUID NetFrameworkConfigurationKey
    # 76944fb33636aeddb9590521c2e8815a_GUID iisWasKey
    
    foreach ($file in [IO.Directory]::EnumerateFiles("C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys", "*.*", "AllDirectories")) {
        # system keys, leave them alone
        if ($file -imatch "6de9cb26d2b98c01ec4e9e8b34824aa2|d6d986f09a1ee04e24c949879fdb506c|76944fb33636aeddb9590521c2e8815a") { continue }
    
        $f = Get-ChildItem $file
        if ($f.CreationTime -le $deleteDate) {
            if (($counter++ % 100) -eq 0) {
                Write-Host "DELETING ($("{0:N0}" -f $counter)) $file" -ForegroundColor Yellow
            }
            $f.Delete()
        } 
    }
    
    Write-Host "DONE"
    

    TY @starball. I always forget....