Storing Any Text Encrypted

by Mar 6, 2023

Let’s say your script needs sensitive input like connection strings for a database or other text information.

One way of managing such secrets is to store them as [SecureString] and serialize this information safely to XML. This is what this part does:

$Path = "$env:temp\safeconnectionstring.test"


[ordered]@{
    Con1 = 'secret1' | ConvertTo-SecureString -AsPlainText -Force
    Con2 = 'secret2' | ConvertTo-SecureString -AsPlainText -Force
    Con3 = 'secret3' | ConvertTo-SecureString -AsPlainText -Force
} | Export-Clixml -Path $Path

It embeds three secrets in a hash table, converts them to secure strings and then exports them safely to XML. The secret is the user and machine that runs this script, so only this person (on the same PC) can later read the information.

If you’d rather not store the secrets anywhere, you can also interactively type them in:

$Path = "$env:temp\safeconnectionstring.test"


[ordered]@{
    Con1 = Read-Host -Prompt Secret1 -AsSecureString
    Con2 = Read-Host -Prompt Secret1 -AsSecureString
    Con3 = Read-Host -Prompt Secret1 -AsSecureString
} | Export-Clixml -Path $Path 

Now, when it is time to use the secrets, you need a way to convert secure strings back to plain text. This is what this script does:

$hash = Import-Clixml -Path $Path
# important: MUST cast $keys to [string[]] or else you cannot modify the hash
# in the loop:
[string[]]$keys = $hash.Keys
$keys | ForEach-Object {
    $hash[$_] = [PSCredential]::new('xyz', $hash[$_]).GetNetworkCredential().Password
}

The result ($hash) is a hash table which contains your secrets in plain text, so in this example you could access your three secrets via the three keys “con1”, “con2”, and “con3”:

 
PS> $hash.Con1
secret1

PS> $hash.Con2
secret2

PS> $hash.Con3
secret3 
 


Tweet this Tip! Tweet this Tip!