Powershell SecureString加密/解密到纯文本不起作用

时间:2014-02-12 23:03:19

标签: powershell encryption

我们试图将用户密码作为安全字符串存储在注册表中,但我们似乎无法找到将其转换回纯文本的方法。这可以通过SecureString实现吗?

以下是我们尝试使用的简单测试脚本......

Write-Host "Test Start..."
$PlainPassword = "@SomethingStupid" | ConvertTo-SecureString -AsPlainText -Force

$BSTR = ` [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($PlainPassword)
$PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
Write-Host "Password is: " $PlainPassword
Read-Host

这是我们得到的错误......

The term ' [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR'
is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\test.ps1:4 char:71
+ $BSTR = ` [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR
<<<< ($PlainPassword)
    + CategoryInfo          : ObjectNotFound: (
[System.Runtim...ureStringToBSTR:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Cannot find an overload for "PtrToStringAuto" and the argument count: "1".
At C:\test.ps1:5 char:75
+ $PlainPassword =
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto <<<< ($BSTR)
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

2 个答案:

答案 0 :(得分:15)

$BSTR = ...行中的反引号是什么?我同意上面的格雷厄姆。如果我删除反引号就可以了:

$PlainPassword = "@SomethingStupid" | ConvertTo-SecureString -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($PlainPassword)
$PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
Write-Host "Password is: " $PlainPassword

输出:

Password is:  @SomethingStupid

您不是试图在Windows RT或其他限制语言的PowerShell配置上运行此操作 - 是吗?

答案 1 :(得分:13)

这里有一个很简单但解密安全字符串的方法,利用了PSCredential class有一个接受密码作为安全字符串和方法的构造函数这一事实( GetNetworkCredential )以纯文本形式返回该密码:

(New-Object System.Management.Automation.PSCredential 'N/A', $secure_string).GetNetworkCredential().Password

虽然它打算与凭证一起使用,但没有什么可以阻止您使用它来解密任何安全字符串*,无论用途如何,为用户名提供伪参数(用户名参数可以&# 39; t为null或空字符串,但任何无意义的字符串都可以)。

<小时/> *在加密安全字符串的帐户的上下文中,当然