Quantcast
Channel: t h e D a v i d A i k e n » PowerShell
Viewing all articles
Browse latest Browse all 3

Encrypting and Decrypting in Windows Azure

$
0
0

When deploying applications to Windows Azure, you probably will be dealing with encrypted connections strings, passwords and other such things. If you have ever used Remote Desktop, you will have noticed an encrypted password, along with a certificate that is used to encrypt the password. You can of course do the same with your secret things too.

Doing this creates the need for a tool to encrypt such settings. There are a few posts out there that show how to decrypt the values in code (you can grab some from here), you still need a way for operators to create these values in the first place. I thought a couple of PowerShell scripts should do the trick nicely.

You will need the thumbprint of a certificate in the CurrentUser\My store, which would be the same cert you deploy with you Azure deployment in order to decrypt.

The Encrypt function looks like:

Function Encrypt($stringToEncrypt, $thumb)
{
    $cert = get-item cert:\CurrentUser\My\$thumb
    [System.Reflection.Assembly]::LoadWithPartialName("System.Security") | out-null
    $passbytes = [Text.Encoding]::UTF8.GetBytes($stringToEncrypt)
    $content = New-Object Security.Cryptography.Pkcs.ContentInfo -argumentList (,$passbytes)
    $env = New-Object Security.Cryptography.Pkcs.EnvelopedCms $content
    $env.Encrypt((new-object System.Security.Cryptography.Pkcs.CmsRecipient($cert)))

    [Convert]::Tobase64String($env.Encode())
}

The Decrypt function looks like:

Function Decrypt($EncryptedString, $thumb)
{    
    $cert = get-item cert:\CurrentUser\My\$thumb    
    [System.Reflection.Assembly]::LoadWithPartialName("System.Security") | out-null
    $encodedBytes = [Convert]::Frombase64String($EncryptedString)
    $env = New-Object Security.Cryptography.Pkcs.EnvelopedCms
    $env.Decode($encodedBytes)
    $env.Decrypt($cert)
    $enc = New-Object System.Text.ASCIIEncoding
    
    $enc.GetString($env.ContentInfo.Content)    
}

Usage is simple:

$pwd = Encrypt "TheDavidAiken" "39836617C1A2BBAC6F90C0224C31B019854C6659"
Decrypt $pwd "39836617C1A2BBAC6F90C0224C31B019854C6659"

Enjoy.

THIS POSTING IS PROVIDED “AS IS” WITH NO WARRANTIES, AND CONFERS NO RIGHTS, UNLESS YOU HAVE A NOTE FROM MY MUM


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images