在 Powershell 中为 TFS 2015.2 使用 REST API 时如何在不在脚本中使用密码的情况下保护密码

While using REST API in Powershell for TFS 2015.2 how to secure your password without using it in the script

虽然我使用了此线程中提到的方法 PowerShell's Invoke-RestMethod equivalent of curl -u (Basic Authentication) 我可以连接到 REST API 而不会出现 401 错误。

但是目前我以纯文本形式提供密码。

我想要一种方法来使用密码的哈希值,然后在脚本中使用它。

脚本应该也能解密它。但我不希望其他有权访问该脚本的人能够解密它。

所以我也不想把解密算法暴露给任何人。

我想到的建议方法: 以混合随机方式组合现有的 HASH 算法(通过将一种算法的 HASH 提供给另一种算法),只有我知道,然后在知道解密的脚本中有一个自定义 Powershell function/cmdlet/whatever。

有没有更简单更好的方法?

在我尝试建议的方法之前,我想听听其他人对任何更好的方法的看法。

整个脚本如下


$User = "domain\userName"
$uri = "https://TeamProjectCollectionURI/TeamProjectName/_apis/build/builds"
$securePassword = ConvertTo-SecureString 'PasswordWhichContains$asWell' -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($User, $securePassword)
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$credential)))
$response = Invoke-RestMethod -Method Get -Uri $uri -Credential $credential -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -ContentType application/json
$response

您可以通过 PowerShell 将用户名和密码(伪装成 秘密变量 )传递到 PSCredential 对象并使用 -Credential调用REST方法时切换:

$securePassword = $Password | ConvertTo-SecureString -AsPlainText -Force   $credential = New-Object System.Management.Automation.PSCredential($User, $securePassword)       
$releaseresponse = Invoke-RestMethod -Method Get -Credential $credential -ContentType application/json -Uri $Uri

更多详细信息请参考此博客:VSTS/TFS REST API: The basics and working with builds and releases

您可以将密码转换为加密字符串并在 PowerShell 脚本中使用加密字符串。

转换为加密字符串:

$securePassword = ConvertTo-SecureString "Yourpassword" -AsPlainText -Force

$encryptedPwd = ConvertFrom-SecureString -SecureString $securePassword

Write-Host $encryptedPwd

记录生成的加密字符串并在您的脚本中使用它。

$securePassword = ConvertTo-SecureString -String "Encrypted String"