PowerShell Scripts, Tips, Expert Advices, Forums, and Resources

Geek Sync Live

Welcome to PowerShell.com, the educational and community site for Windows PowerShell People. Get a quick overview.

As a Powershell.com member you will have access to:

  • Daily PowerShell tips written by Microsoft MVPs and other leading Windows PowerShell experts
  • Free Windows PowerShell advice and training provided by Microsoft MVPs and other leading Windows PowerShell experts
  • Access to leading Windows PowerShell blogs
  • A free ebook, Mastering PowerShell, written by Microsoft MVP Dr. Tobias Weltner
PowerTip of the Day

Encrypting Text

There are many ways to encrypt text. Here is an approach that does not use an explicit “secret”. Instead, the secret is defined as your identity plus your machine.

When you encrypt text using ConvertTo-TextEncrypted, the result can only be deciphered by ConvertFrom-TextEncrypted if the same person runs the command on the same machine:

#requires -Version 2

function ConvertTo-TextEncrypted
    param([Parameter(ValueFromPipeline = $true)]$Text)

        $Text | 
        ConvertTo-SecureString -AsPlainText -Force |

function ConvertFrom-TextEncrypted
    param([Parameter(ValueFromPipeline = $true)]$Text)

        $SecureString = $Text |

        $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)

To test the process, try this first:

PS> "Hello World" | ConvertTo-TextEncrypted | ConvertFrom-TextEncrypted
Hello World

Next, take some secret text, encrypt it, and save it in a file:

$Path = "$env:temp\secret.txt"
'Hello World' | ConvertTo-TextEncrypted | Set-Content -Path $Path

Now, try this to read in the saved encrypted text, and decipher it:

$Path = "$env:temp\secret.txt"
Get-Content -Path $Path | ConvertFrom-TextEncrypted 

Note that neither script contains a secret passphrase. Instead, your identity is the passphrase. So when someone else tries to decipher the text in the file, or when you try to decipher it on another computer, it fails.

The approach shown here can be used to safely store personal passwords that you do not want to manually enter every day.

Twitter This Tip! ReTweet this Tip!

Copyright 2012 PowerShell.com. All rights reserved.