我已经将凭据存储在 xml 文件中。
$myCredential=Get-Credential -Message "Enter the credentials."
$myCredential | Out-File "C:\cred.xml"
Run Code Online (Sandbox Code Playgroud)
现在,我有一个脚本,在运行时会提示并获取新凭据。
$newCredential= Get-Credential -Message "Enter your credential."
Run Code Online (Sandbox Code Playgroud)
那么,如何检查新提供的凭据是否与旧凭据匹配,而不将凭据解密为人类可理解的实际纯文本?
以下是如何安全地比较两个SecureString对象而不解密它们:
# Safely compares two SecureString objects without decrypting them.
# Outputs $true if they are equal, or $false otherwise.
function Compare-SecureString {
param(
[Security.SecureString]
$secureString1,
[Security.SecureString]
$secureString2
)
try {
$bstr1 = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString1)
$bstr2 = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString2)
$length1 = [Runtime.InteropServices.Marshal]::ReadInt32($bstr1,-4)
$length2 = [Runtime.InteropServices.Marshal]::ReadInt32($bstr2,-4)
if ( $length1 -ne $length2 ) {
return $false
}
for ( $i = 0; $i -lt $length1; ++$i ) {
$b1 = [Runtime.InteropServices.Marshal]::ReadByte($bstr1,$i)
$b2 = [Runtime.InteropServices.Marshal]::ReadByte($bstr2,$i)
if ( $b1 -ne $b2 ) {
return $false
}
}
return $true
}
finally {
if ( $bstr1 -ne [IntPtr]::Zero ) {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr1)
}
if ( $bstr2 -ne [IntPtr]::Zero ) {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr2)
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用上面的函数来比较Password两个PSCredential对象的属性:
$theyMatch = Compare-SecureString $cred1.Password $cred2.Password
if ( $theyMatch ) {
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2113 次 |
| 最近记录: |