你如何在powershell中解密securestring

new*_*mer 3 powershell

$Variable = Read-Host "Enter thing" -AsSecureString
Run Code Online (Sandbox Code Playgroud)

将提示您输入并将其保存为变量的安全字符串。如何解密安全字符串变量?

PS C:\Users\Todd> $Variable
System.Security.SecureString
Run Code Online (Sandbox Code Playgroud)

mkl*_*nt0 5

首先是安全警告:

将安全字符串转换为常规[string]实例违背了使用[securestring]( System.Security.SecureString) 开始的目的:您最终将在您无法控制的进程内存中以纯文本形式表示敏感数据。

另外,请注意,通常不再推荐在新代码中使用安全字符串:它们仅在 Windows 上提供有限的保护,在类 Unix 平台上提供的保护更少,在这些平台上它们甚至没有加密。


PowerShell v7+现在提供ConvertFrom-SecureString -AsPlainText将安全字符串转换为其 - 不安全 - 纯文本表示:

# PowerShell 7.0 or higher.
$password = Read-Host "Enter password" -AsSecureString
$plainTextPassword = ConvertFrom-SecureString -AsPlainText $password
Run Code Online (Sandbox Code Playgroud)

在PowerShell v6-(包括 Windows PowerShell)中,您可以使用以下内容:

$password = Read-Host "Enter password" -AsSecureString
$plainTextPassword = [Net.NetworkCredential]::new('', $password).Password
Run Code Online (Sandbox Code Playgroud)


Nic*_*oru 3

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

要将Read-Host SecureStrings 转换为普通字符串,您可以使用

$NewVaraible = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($ReadVariable)
$NewNewVariable = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($NewVariable)
Run Code Online (Sandbox Code Playgroud)

或者您可以只更新现有变量:

$ReadVaraible = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($ReadVariable)
$ReadVariable = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ReadVariable)
Run Code Online (Sandbox Code Playgroud)
感谢@mklement0 的富有洞察力的评论;根据 mklement0 的评论更新了答案

  • 我知道“PtrToStringAuto()”的使用很常见,但它在概念上有缺陷,并且在类 Unix 平台上会崩溃;使用 `PtrToStringBSTR()` 代替 - 请参阅[此答案](/sf/answers/4228487791/)。另外,还有一些通常会丢失的东西,您应该随后调用“[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($NewVariable)”,以清零并释放 BSTR。 (3认同)