How to Decrypt: Method 1 and 2
# Method 1 $Decrypted = [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($InputSecureString)) # Method 2 $temp = New-Object PSCredential ("Decrypt", $InputSecureString) $Decrypted = $temp.GetNetworkCredential().Password
Example - Method 1
In method 1 we use the Marshal class of the Microsoft .Net framework. The class has a SecureStringToBSTR method that converts our SecureString to a binary string that is human readable.
# Generate a SecureString object to work with as an example PS C:\> $SecureString = ConvertTo-SecureString "SuperSecret!" -AsPlainText -Force # Method 1 PS C:\> $Decrypted = [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($SecureString)) PS C:\> $Decrypted SuperSecret! PS C:\>
Example - Method 2
Method 2 offers us a simplified code at the expense of performance degradation. We build a PSCredential object first, which object has a GetNetworkCredential method which converts the SecureString for us and stores it in the Password property of the resulting object.
# Generate a SecureString object to work with as an example PS C:\> $SecureString = ConvertTo-SecureString "SuperSecret!" -AsPlainText -Force # Method 2 PS C:\> $temp = New-Object PSCredential ("Decrypt", $SecureString) PS C:\> $Decrypted = $temp.GetNetworkCredential().Password PS C:\> $Decrypted SuperSecret! PS C:\>
Comments