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

From Host Input

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

The result is a SecureString

PS> $SecureStringPassword

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

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

Generate Random Encryption Key

$Key = New-Object Byte[] 16   # You can use 16, 24, or 32 for AES

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

PS> $key -join ','

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.