≡ Menu

Compare secure strings entered through powershell

Can’t we really see the text/password entered through -AsSecureString or with Get-Credential? What I have to do if I got a requirement to compare the passwords? The example scenario for me as a System administrator is, if I have a script which resets admin password acrosss a list of hosts, I will prefer the script to ask for the password two times in secure format and inturn my script should compare these two passwords and proceed only if the passwords entered at two attempts is matched.

In one of the powershell blog author talked about seeing the secure text in plain format. I used that and developed below script for comparing the passwords using powershell.

Write-Host "Hey..!! I am here to compare the password you are entering..."
$pwd1 = Read-Host "Passowrd" -AsSecureString
$pwd2 = Read-Host "Re-enter Passowrd" -AsSecureString
$pwd1_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd1))
$pwd2_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd2))

if ($pwd1_text -ceq $pwd2_text) {
Write-Host "Passwords matched"
} else {
Write-Host "Passwords differ"

Let me know if you have any comments/questions…

{ 5 comments… add one }
  • Jonathan Santos November 23, 2012, 2:42 am

    Very Good!


  • Ronan Fahy December 11, 2012, 8:19 pm

    Hi – nice script but one small problem, you’re not handling case sensitivity – i.e. ABC and abc and AbC are all coming out as matching passwords. If you used:

    if ($pwd1_text.compareTo($pwd2_text) -eq 0) it’ll work.

    • Sitaram Pamarthi December 11, 2012, 9:58 pm

      That is very good point. I think using case sensitive equal comparator in Powershell is very easy. I updated the code to include -ceq instead of -eq.
      Thanks for highlighting that.

  • Alex November 24, 2015, 8:22 pm

    An even smaller problem, you have a typo in password. Unless you were planning on developing a new cereal, pass-o-wrds. And if you are, I would certainly like some.

    Thanks for the script. Can you elaborate where “[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR” comes from?

Leave a Comment