Using SecureString in PowerShell (With Key)

Here is the example of using SecureString, when 16 bytes key is used. Using key we can overcome the problem – “decryption of password can only be done by same user on same machine which were used for encryption”, as mentioned in my earlier post.

1. Generate key, encrypt password and save both key and encrypted password


$textPassword = "withkey-textpassword"
$key = New-Object Byte[] 16 # You can use 16, 24, or 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)

$securePassword = ConvertTo-SecureString $textPassword -AsPlainText -Force
$encryptedPassword = ConvertFrom-SecureString $SecurePassword -Key $Key

$encryptedPassword | Out-File "c:\temp\withkey-encpass.txt"
$key | Out-File "c:\temp\withkey-plainkey.txt"

Write-Host "Key: $Key"
Write-Host "Encrypted Password: $encryptedPassword"

2. Retrieve key and password then decrypt password using the key


$encryptedPassword = Get-Content "C:\temp\withkey-encpass.txt"
$key = Get-Content "C:\temp\withkey-plainkey.txt"
$secureDecryptedPassword = ConvertTo-SecureString -string $encryptedPassword -Key $key

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureDecryptedPassword)
$textPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

$credentials = New-Object System.Net.NetworkCredential("TestUsername", $secureDecryptedPassword, "TestDomain")

Write-Host "Key: $Key"
Write-Host "Encrypted Password: $encryptedPassword"
Write-Host "Text Password: $textPassword"
Write-Host ("Text Password without marshaling: {0}" -f $credentials.Password)

Leave a comment