I am trying to encrypt & decrypt a string with ConvertTo-SecureString
, output the string plaintext, and verify that the key works correctly to decrypt the string in PowerShell.
I'm expecting it to output "Hello World", but I'm getting an unexpected string instead.
How Can I fix this? I cannot use Security.Cryptography
classes because this script is designed to run in a restricted execution policy environment where Add-Type
cannot be used.
$encryptionKey = (13, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
$stringToEncrypt = "Hello World"
$stringToEncrypt | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString -Key $encryptionKey | Out-File -FilePath key.txt
$decrypted = Get-Content key.txt | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString -Key $encryptionKey
Write-Host $decrypted # The Decrypted String, expected to be "Hello World"
CodePudding user response:
Very close. It looks like you may have just mixed parameters on the decryption part. With ConvertTo-SecureString
and ConvertFrom-SecureString.
ConvertTo-SecureString -Key $encryptionKey
will first decrypt your encrypted string and convert to a secure string. ConvertFrom-SecureString -AsPlainText
is then going to convert the secure string back into a plain text string.
Change the line
# change this
$decrypted = Get-Content key.txt | ConvertTo-SecureString-AsPlainText -Force | ConvertFrom-SecureString -Key $encryptionKey
# to this
$decrypted = Get-Content key.txt | ConvertTo-SecureString -Key $encryptionKey | ConvertFrom-SecureString -AsPlainText
See the documentation for ConvertFrom-SecureString and ConvertTo-SecureString for some more examples and explanations.