This blog details how to encrypt and decrypt a string or password via PowerShell.
Open a PowerShell ISE Editor as an Administrator and check your PS Version. The full article is tested on 5.X PS version shown below.
Encryption:
Let’s first understand how encryption works in PowerShell.
Here we have taken the string “Welcome@123” in a PWD variable and simply echoed it.
Now, let us try to encrypt it.
The first step would be the normal string “Welcome@123” converted into a secure string, using ConvertTo-SecureString cmdlet.
This secure string needs to be further encrypted using ConvertFrom-SecureString cmdlet.
$pwd = “Welcome@123”
$securepwd = $pwd | ConvertTo-SecureString -AsPlainText -Force
$securepwd | ConvertFrom-SecureString
The encrypted string can be stored in the file for further use or can be stored in a variable as per the requirement.
Encryption Code:
$pwd = “Welcome@123”
$securepwd = $pwd | ConvertTo-SecureString -AsPlainText -Force
$encryptedpwd = $securepwd | ConvertFrom-SecureString
write-host $encryptedpwd
Encryption Code (Image by Nikhil Sureka)
Decryption:
Now let's see how decryption works in PowerShell.
We have the encrypted password stored in a variable as shown above.
write-host $encryptedpwd
Now to decrypt the encrypted string, we will go a reverse way. We will first convert the encrypted string back to a secure string using ConvertTo-SecureString cmdlet.
$securepwd = $encryptedpwd | ConvertTo-SecureString
write-host $securepwd
PowerShell uses the .Net Framework libraries, here Marshal class from System.Runtime.InteropServices namespace with PtrToStringAuto and SecureStringToBSTR methods to convert the encrypted String to plain text.
$Marshal = [System.Runtime.InteropServices.Marshal]
write-output $Marshal
SecureStringToBSTR — Allocates an unmanaged binary string (BSTR) and copies the contents of a managed SecureString object into it.
$Bstr = $Marshal::SecureStringToBSTR($securepwd)
write-output $Bstr
PtrToStringAuto — Allocates a managed string and copies all or part of an unmanaged string into it. The PWD variable will have the plain text string or password as stored.
$pwd = $Marshal::PtrToStringAuto($Bstr)
write-host $pwd
The ZeroFreeBSTR is to clear the unmanaged memory
$Marshal::ZeroFreeBSTR($Bstr)
Below is the Decryption code to decrypt an encrypted string or password.
Decryption Code:
$securepwd = $encryptedpwd | ConvertTo-SecureString
$Marshal = [System.Runtime.InteropServices.Marshal]
$Bstr = $Marshal::SecureStringToBSTR($securepwd)
$pwd = $Marshal::PtrToStringAuto($Bstr)
Write-host $pwd
$Marshal::ZeroFreeBSTR($Bstr)
Hope this blog will help to perform the encryption and decryption in PowerShell.
References: