Create a New Key in Microsoft Enhanced RSA and AES Cryptographic Provider (PowerShell)

# Function to generate a new key in the CSP
#Display All: certutil -csp “Microsoft Enhanced RSA and AES Cryptographic Provider” -key
#Display One: certutil -csp “Microsoft Enhanced RSA and AES Cryptographic Provider” -key “_DRMS:Mode2:MS-GUID:{f15ac94b-a1d7-471f-a338-a37f8f56c20e}”
#
function New-RSAKeyInCSP {
param(
[int]$KeySize = 2048,
[string]$ContainerName = “MyNewKey_$(Get-Date -Format ‘yyyyMMddHHmmss’)”,
[bool]$MachineKey = $true,
[string]$CSPName = “Microsoft Enhanced RSA and AES Cryptographic Provider”
)

try {
# Create CSP parameters
$cspParams = New-Object System.Security.Cryptography.CspParameters
$cspParams.ProviderName = $CSPName
$cspParams.ProviderType = 24 # PROV_RSA_AES
$cspParams.KeyContainerName = $ContainerName

if ($MachineKey) {
$cspParams.Flags = [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore
}

# Generate the key pair
$rsa = New-Object System.Security.Cryptography.RSACryptoServiceProvider($KeySize, $cspParams)

Write-Host “Key generated successfully!” -ForegroundColor Green
Write-Host “Container Name: $ContainerName” -ForegroundColor Yellow
Write-Host “Key Size: $KeySize bits” -ForegroundColor Yellow
Write-Host “Machine Key: $MachineKey” -ForegroundColor Yellow
Write-Host “Provider: $CSPName” -ForegroundColor Yellow

# Clean up
$rsa.Clear()
$rsa.Dispose()

return $ContainerName

} catch {
Write-Error “Failed to generate key: $($_.Exception.Message)”
return $null
}
}

# Generate the key
$keyContainer = New-RSAKeyInCSP -KeySize 2048 -ContainerName “_DRMS:Mode2:MS-GUID:{xxxxxxxxxx}” -MachineKey $true