比较powershell中的两个凭据 [英] Compare two credentials in powershell
本文介绍了比较powershell中的两个凭据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经将我的凭据存储在一个 xml 文件中.
I already have my credentials stored in an xml file.
$myCredential=Get-Credential -Message "Enter the credentials."
$myCredential | Out-File "C:\cred.xml"
现在,我有一个脚本,它在运行时会提示并获取新凭据.
Now, I have a script that prompts and gets new credential when it is run.
$newCredential= Get-Credential -Message "Enter your credential."
那么,如何在不将凭据解密为人类可理解的实际纯文本的情况下检查新提供的凭据是否与旧凭据匹配?
So, how do I check if the newly provided credential is matching with the old credential without decrypting the credentials to human understandable actual plain text?
推荐答案
这里是如何安全地比较两个 SecureString
对象而不解密它们:
Here is how to securely compare two SecureString
objects without decrypting them:
# 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)
}
}
}
您可以使用上述函数来比较两个PSCredential
对象的Password
属性:
You can use the above function to compare the Password
property of two PSCredential
objects thus:
$theyMatch = Compare-SecureString $cred1.Password $cred2.Password
if ( $theyMatch ) {
...
}
这篇关于比较powershell中的两个凭据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文