Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you decrypt securestring in powershell [duplicate]

Tags:

powershell

$Variable = Read-Host "Enter thing" -AsSecureString

Will prompt you for input and save it as a secure string to variable. How do I decrypt a secure string variable?

PS C:\Users\Todd> $Variable
System.Security.SecureString
like image 699
newbie programmer Avatar asked Aug 25 '26 06:08

newbie programmer


2 Answers

A security warning first:

Converting a secure string to a regular [string] instance defeats the very purpose of using [securestring] (System.Security.SecureString) to begin with: you'll end up with a plain-text representation of your sensitive data in your process' memory whose lifetime you cannot control.

Also, note that secure strings are generally not recommended for use in new code anymore: they offer only limited protection on Windows, and virtually none on Unix-like platforms, where they aren't even encrypted.


PowerShell (Core) 7 now offers ConvertFrom-SecureString -AsPlainText to convert a secure string to its - unsecured - plain-text representation:

  • PowerShell 7.0 or higher:

    # PowerShell 7.0 or higher.
    $password = Read-Host "Enter password" -AsSecureString
    $plainTextPassword = ConvertFrom-SecureString -AsPlainText $password
    
  • More directly, in PowerShell 7.1 or higher, you can use Read-Host's new -MaskInput switch in order to mask user input (with * chars.), while still returning a plain-text string:

    # PowerShell 7.1 or higher.
    $plainTextPassword = Read-Host "Enter password" -MaskInput
    

In Windows PowerShell, you can use the following:

$password = Read-Host "Enter password" -AsSecureString
$plainTextPassword = [Net.NetworkCredential]::new('', $password).Password
like image 73
mklement0 Avatar answered Aug 26 '26 20:08

mklement0


$password = Read-Host "Enter password" -AsSecureString
$password = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
$password = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($password)
echo $password
pause

To convert Read-Host SecureStrings to normal strings, you use

$NewVaraible = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($ReadVariable)
$NewNewVariable = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($NewVariable)

Or you could just update the existing variable:

$ReadVaraible = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($ReadVariable)
$ReadVariable = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ReadVariable)

Thank you @mklement0 for your insightful comments; updated answer accordingly to mklement0's comment
like image 39
Nico Nekoru Avatar answered Aug 26 '26 21:08

Nico Nekoru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!