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

dev*_*nkd 9 encryption powershell

我们试图将用户密码作为安全字符串存储在注册表中,但我们似乎无法找到将其转换回纯文本的方法.这可以通过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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

Kei*_*ill 18

$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
Run Code Online (Sandbox Code Playgroud)

输出:

Password is:  @SomethingStupid
Run Code Online (Sandbox Code Playgroud)

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


Adi*_*bar 14

这是解密安全字符串的一种简单但更简单的方法,利用PSCredential类具有接受密码作为安全字符串的构造函数和以纯文本形式返回该密码的方法(GetNetworkCredential):

(New-Object System.Management.Automation.PSCredential 'N/A', $secure_string).GetNetworkCredential().Password
Run Code Online (Sandbox Code Playgroud)

虽然它打算与凭证一起使用,但没有什么可以阻止你使用它来解密任何安全字符串*,无论用途如何,为用户名提供伪参数(username参数不能为null或空字符串,但任何无意义字符串会做).


*当然,在加密安全字符串的帐户的上下文中

  • 完善.它允许我检索存储在文件中的先前ConvertTo-SecureString密码,然后将其传递给Invoke-SqlCmd. (2认同)