1

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"

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.