如何正确输入和存储安全密码?我需要从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并返回简单的纯文本密码。
EDIT;
我有以下获取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正在抱怨。
答案 0 :(得分:0)
不建议用于生产系统,但请尝试以下方法:
$secpass = Read-Host -assecurestring "Please enter password"
$credentials = New-Object System.Net.NetworkCredential("UserTest", $secpass, "Domain")
$credentials.Password
使用ConvertFrom-SecureString
无法做到这一点