Using PowerShell to check Pwned passwords (Using the HaveIBeenPwned API)

We’ve been encountering a lot of Office365 hacks in the previous months. Most of the time the client does not want MFA enabled and has no clue their password has already been leaked. We figured internally that we’d like a way to check if a single password has been leaked but as we are the purest of nerds we hate browsing to a website. 😉 Enter PowerShell! We’ve created a small script that checks multiple passwords using the HaveIBeenPwned API to check if the password has been seen in a leak before.

To generate a hash of the password we are entering, we’re using Get-StringHash made by Jon Gurgul. To find the get-stringhash function you can visit the PowerShell gallery here or read Jon’s blog about it here

$passwords = @("PlainTextPassword","NotMyPassword","WhyGodWhy","password")

#http://jongurgul.com/blog/get-stringhash-get-filehash/ 
Function Get-StringHash([String] $String,$HashName = "SHA1") 
{ 
$StringBuilder = New-Object System.Text.StringBuilder 
[System.Security.Cryptography.HashAlgorithm]::Create($HashName).ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String))|%{ 
[Void]$StringBuilder.Append($_.ToString("x2")) 
} 
$StringBuilder.ToString() 
}


foreach($Password in $passwords){
$hash = Get-StringHash -String $($Password) -HashName SHA1
$APICall = $hash.Substring(0,5)
$APIResult = Invoke-Restmethod -Uri "https://api.pwnedpasswords.com/range/$APICall"
$APIresult = $APIresult -split "`n"
$FoundMatch = $APIResult | Where-Object {$_ -match $Hash.Substring(5)}
if($FoundMatch){ write-host "Hash for password $($Password) has been found. Password has most likely been pwned" }
}

The script itself is pretty simple, enter the passwords you want to check into the $Passwords array and run the script, First we’ll load Jon’s function and after that we loop through the password array and write out if the password is encountered.

Attention: Passwords are printed as plain-text and must be entered as plaintext, as always. be careful and happy PowerShelling!

Follow me

Kelvin Tegelaar

I am a Microsoft Certified System Engineer working as the CTO of the Managed Services Provider Lime Networks B.V. in the Netherlands. I mostly enjoy automating business processes by deploying PowerShell solutions, but just have a large passion for Microsoft Technology in general.

If you want to contact me directly you can find me on twitter here, or via email: Kelvin {at} limenetworks.nl
Kelvin Tegelaar
Follow me

1 thought on “Using PowerShell to check Pwned passwords (Using the HaveIBeenPwned API)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.