【问题标题】:How to handle PowerShell Secure Strings如何处理 PowerShell 安全字符串
【发布时间】:2017-02-03 15:37:35
【问题描述】:

如何正确输入和存储安全密码?我需要将其从 Secure 转换为 JSON 以获取 REST 令牌。

我的例子是:

PS C:\Temp> $secpass = Read-Host -assecurestring "请输入密码";

请输入密码:*****

PS C:\Temp> echo $secpass

System.Security.SecureString

PS C:\Temp> $pass = ConvertFrom-SecureString $secpass

PS C:\Temp> echo $pass 01000000d08c9ddf0115d1118c7a00c04fc297eb010000004fe37b5a39a93542a74298c3740cae0b0000000002000000000003660000c00000001000000096aa9947681adf56ce6f9fd2d9ced2140000000004800000a0000000100000006bbff8b1e2115682e9be4c775d8372ee10000000b80a4a99147901275a9080c257712b1914000000010eabc8c134837751dbd2d648dbbca1f7335e9f

PS C:\Temp>

我想运行 ConvertFrom-SecureString 并取回我的简单纯文本密码。

编辑;

我有以下获取 REST 令牌的函数:

function Get-AuthToken {
    Param(
        [string]$server,
        [string]$username,
        [securestring]$password
    )

        $creds = @{
        username = $username
        password = $password
        grant_type = "password"
        };

    Invoke-RestMethod -Method Post "$server/api/token" -Body $creds

}

要正确构建 $creds,密码必须是纯文本。

此外,我还有以下内容来涵盖脚本运行时未提供密码字符串的情况:

If(!$Password) {
            [ValidatePattern("\w+")]$password = Read-Host -assecurestring "Please enter password";
            }

根据此处Convert a secure string to plain text 给出的第一个答案,我尝试在调用 Get-AuthToken 函数之前添加以下内容:

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
$unsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
$response = Get-AuthToken -username $User -password $unsecurePassword -server $server

如果我执行 Write-Host $unsecurePassword 我可以看到正确的字符串,但是 Get-AuthToken 身份验证失败。

编辑 2:

如果我将函数更改为:

function Get-AuthToken {
        Param(
            [string]$server,
            [string]$username,
            [string]$password
        )

            $creds = @{
            username = $username
            password = $password
            grant_type = "password"
            };

        Invoke-RestMethod -Method Post "$server/api/token" -Body $creds

    }

这使 $password 参数成为字符串而不是安全字符串,然后它可以工作,但是不要相信这是最佳实践,因为 Visual Studio Code 会抱怨。

【问题讨论】:

标签: powershell


【解决方案1】:

不建议用于生产系统,但试试这个:

$secpass = Read-Host -assecurestring "Please enter password"
$credentials = New-Object System.Net.NetworkCredential("UserTest", $secpass, "Domain")
$credentials.Password

ConvertFrom-SecureString 无法做到这一点

【讨论】:

  • I want to run the ConvertFrom-SecureString and get my simple plain text password back.
  • @Shmukko - 如果它不适合生产系统,我不确定我是否要这样做。有关更多详细信息,请参阅我上面的编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-31
  • 2016-08-28
  • 2011-12-24
  • 2011-03-26
  • 1970-01-01
  • 2011-12-11
相关资源
最近更新 更多