Working with SecureString in PowerShell

Create SecureString

  • From plain-text String
  • From host input

There are other ways or sources of SecureString , e.g. Key Vault secrets, but we will limit to basic cases only as they give enough coverage and understanding to handle also other situations.

From Plain Text String

$SecureString = ConvertTo-SecureString -String "<strong-password>" -AsPlainText -Force

The actual string is not accessible:

PS> $SecureStringPassword
System.Security.SecureString

From Host Input

$SecureStringPassword = Read-Host -AsSecureString -Prompt "Give me a password"

The result is a SecureString

PS> $SecureStringPassword
System.Security.SecureString

Get Encrypted String From SecureString

$SecureString = ConvertTo-SecureString -String "<strong-password>" -AsPlainText -Force
$key = 1..16

$EncryptedString = ConvertFrom-SecureString -SecureString $SecureString -Key $key

The result from above might look like the following:

PS> $EncryptedString
76492d1116743f04...gA2ADgA

Get Plaintext String from SecureString

$SecureString = ConvertTo-SecureString -String "<strong-password>" -AsPlainText -Force

$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)
$InsecureString = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)

The result:

PS> $InsecureString
<strong-password>

Generate Random Encryption Key

$Key = New-Object Byte[] 16   # You can use 16, 24, or 32 for AES
Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)

If you inspect the value of the $key variable, you will find something like:

PS> $key -join ','
89,74,74,16,145,92,107,80,9,7,170,63,121,210,85,225

Each time you generate a key, the content of the key will be different.

Create Credential Object

  • Using Get-Credential cmdlet
  • Using PSCredential constructor

Using Get-Credential cmdlet

$Credential = Get-Credential

Using PSCredential Constructor

$Credential = New-Object System.Management.Automation.PSCredential($username, $password)
  • $username is a plaintext username
  • $password is a SecureString password

This article was originally published on my blog: Working with SecureString in PowerShell.