When there is the need to encrypt sensitive data, scripts always face the challenge to protect the secret key used to decrypt. If the secret is to be read from the same person that encrypted it, for example, a password that you use in your daily routine scripts, you can use your identity as secret.
This will encrypt a string with your identity:
# File used to store the encrypted string $SecretFile = "$homeDesktopsecret.txt" # Secret string $SecretContent = 'this text is secret!' # Save the password ConvertTo-SecureString -String $SecretContent -AsPlainText -Force | ConvertFrom-SecureString | Out-File $SecretFile -Encoding UTF8 notepad $SecretFile
As you see, the text file contains scrambled data. To turn the scrambled data back into original string data, use this:
# File used to store the encrypted string $SecretFile = "$homeDesktopsecret.txt" $SecureString = ConvertTo-SecureString -String (Get-Content $SecretFile) $Pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString) $SecretContent = [Runtime.InteropServices.Marshal]::PtrToStringAuto($Pointer) $SecretContent
Note that the secret used to encrypt and decrypt the data is composed of your identity and your machine identity, so the encrypted text can only be read by you, and only on the machine where it was originally encrypted.