我有一个从文件读取密码的powershell脚本,密码已使用生成的AES密钥“保护”。过程中使用了三个文件
AES密钥文件生成:
$KeyFile = "\\server\path\AES.key"
$Key = New-Object Byte[] 16
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
$Key | out-file $KeyFile
密码文件生成:
$PasswordFile = "\\server\path\Password.txt"
$KeyFile = "\\server\path\AES.key"
$Key = Get-Content $KeyFile
$Password = "Sy$tem@dmin" | ConvertTo-SecureString -AsPlainText -Force
$Password | ConvertFrom-SecureString -key $Key | Out-File $PasswordFile
获取密码文件并转换回纯文本的脚本:
$User = "myuser"
$PasswordFile = "\\server\path\Password.txt"
$KeyFile = "\\server\path\AES.key"
$key = Get-Content $KeyFile
$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString -Key $key)
$PlainPassword2 = $MyCredential.GetNetworkCredential().Password
$PlainPassword2
转换回纯文本的过程确实正在进行,因此我们可以验证数据是否与最初创建的数据相同。
当我们显示$ PlainPassword2中包含的数据而不是按预期看到 Sy $ tem @ dmin 时,我们看到 Sy @ dmin 。
我们可以做些什么来纠正这个问题?
答案 0 :(得分:2)
转换原始密码字符串时使用的是双引号:
$Password = "Sy$tem@dmin" | ConvertTo-SecureString -AsPlainText -Force
由于"
允许字符串插值,解析器会尝试展开$tem
,因为它可能不存在会导致空字符串,因此您最终会得到您在你的输出。
改为使用单引号:
$Password = 'Sy$tem@dmin' | ConvertTo-SecureString -AsPlainText -Force