比较PowerShell中的两个凭据

时间:2018-02-15 13:57:20

标签: powershell

我已将我的凭据存储在xml文件中。

$myCredential=Get-Credential -Message "Enter the credentials."
$myCredential | Out-File "C:\cred.xml"

现在,我有一个脚本在运行时会提示并获取新凭据。

$newCredential= Get-Credential -Message "Enter your credential."

那么,如何检查新提供的凭证是否与旧凭证匹配,而无需将凭据解密为人类可理解的实际纯文本?

2 个答案:

答案 0 :(得分:1)

以下是如何安全地比较两个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)
    }
  }
}

您可以使用上面的函数来比较两个Password对象的PSCredential属性:

$theyMatch = Compare-SecureString $cred1.Password $cred2.Password
if ( $theyMatch ) {
  ...
}

答案 1 :(得分:0)

您可以使用GetNetworkCredential()方法获取纯文本而不将其保存在任何位置,只需验证即可。

if ($newCredential.GetNetworkCredential().Password -eq $oldCredential.GetNetworkCredential().Password )
{
return "Password is match"
}