我正在尝试为Web应用程序上的某些服务帐户建立基本凭证存储。我有一个网页,我输入了用户名和密码,并将其发布到下面的代码
Param
(
[Parameter(Mandatory = $true)] $Username,
[Parameter(Mandatory = $true)] $Password
)
$secpwd = $Password | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
$newline = "$($Username),$($secpwd)"
$newline | Add-Content "..\Database\accounts.csv"
无论出于什么原因,我得到的都是用户名,而在csv中则空白,我无法完全确定原因。我确实使用从命令行收集的参数在本地重写了该代码,并且该测试有效。在此代码的早期版本中,它实际上将返回纯文本密码。
编辑:我添加了try / catch的输出:ConvertFrom-SecureString : The data protection operation was unsuccessful. This may have been caused by not having the user profile loaded for the current thread's user context, which may be the case when the thread is impersonating.
答案 0 :(得分:1)
我想我明白了。我认为由于这是一个网站,因此它没有用户登录。由于没有,我必须使用密钥来加密密码。所以现在我的代码如下:
Param
(
[Parameter(Mandatory = $true)] $Username,
[Parameter(Mandatory = $true)] $Password
)
try {
$key = Get-Content "..\Database\keyfile.key"
$secpwd = $Password | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString -key $key
$newline = "$($Username),$($secpwd)"
$newline | Add-Content "..\Database\accounts.csv"
}
catch {
$Error
}
此外,这是在密钥文件中生成密钥的代码:
$keyfile = "..\Database\keyfile.key"
$key = New-Object Byte[] 16
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($key)
$key | out-file $keyfile