Thursday, September 1, 2011

PowerShell to select a certificate and encrypt a password

Here is a quick little script to encrypt a password with PowerShell.  Yes, it requires the user to select a certificate and enter the password but that could be easy to change.. 

I have found this very handy when encrypting passwords for use in Azure Role settings, such as Azure Connect.  Secure String does not work as in Azure my local machine keys are not available, however I can use a Service Certificate to encrypt on my end and therefore decrypt on the Azure end.

I have one assumption – that the certificate is in the LocalMachine Personal certificate store.

$password = Read-Host -Prompt "Enter the password to encrypt"

$certs = dir cert:\LocalMachine\My
[System.Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null
$collection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certs | ForEach-Object { $collection.Add($_) } | Out-Null
$cert = [System.Security.Cryptography.x509Certificates.X509Certificate2UI]::SelectFromCollection($collection, "", "Select a certificate", 0)
$thumbprint = $cert[0].thumbprint
$pass = [Text.Encoding]::UTF8.GetBytes($password)
$content = new-object Security.Cryptography.Pkcs.ContentInfo -argumentList (,$pass)
$env = new-object Security.Cryptography.Pkcs.EnvelopedCms $content
$env.Encrypt((new-object System.Security.Cryptography.Pkcs.CmsRecipient(gi cert:\LocalMachine\My\$thumbprint)))
write-host "Writing encrypted password, cut/paste the text below the line to CSCFG file"
[Convert]::ToBase64String($env.Encode()) | Out-File .\encrypted_password.txt
Invoke-Item ".\encrypted_password.txt"

3 comments:

Anonymous said...

This is excellent, thanks! One tweak, if you care to use it, would be to pipe the encrypted string to your clipboard, instead of writing to file (unless of course you NEED to have the encrypted password in a file)... So the line would be:

[Convert]::ToBase64String($env.Encode()) | clip

and that would make it go to your clipboard, ready for pasting :)

Anonymous said...

awesome.. i also came here just searching for a way to encrypt a password for azure.

works like a charm!!

Anonymous said...

awesome.. i also came here just searching for a way to encrypt a password for azure.

works like a charm!!