PowerShell 3.0 and later
In a previous tip we explained how you can use the Windows product ID stored in the Windows Registry to encrypt some text information.
If you find that this publicly available information is not safe enough for your purpose, then you can use a secret encryption key of your choice instead. The following example illustrates how a secret passphrase can be used as encryption key:
$Path = "$env:temp\secret.txt" $Secret = 'Hello World!' $Passphrase = 'Some secret key' $key = [Byte[]]($Passphrase.PadRight(24).Substring(0,24).ToCharArray()) $Secret | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString -Key $key | Out-File -FilePath $Path notepad $Path
To decipher the encrypted text, you would need to know the passphrase used to encrypt the text:
$Passphrase = Read-Host 'Enter the secret pass phrase' $Path = "$env:temp\secret.txt" $key = [Byte[]]($Passphrase.PadRight(24).Substring(0,24).ToCharArray()) try { $decryptedTextSecureString = Get-Content -Path $Path -Raw | ConvertTo-SecureString -Key $key -ErrorAction Stop $cred = New-Object -TypeName System.Management.Automation.PSCredential('dummy', $decryptedTextSecureString) $decryptedText = $cred.GetNetworkCredential().Password } catch { $decryptedText = '(wrong key)' } "The decrypted secret text: $decryptedText"