Last active
November 16, 2022 22:02
-
-
Save SP3269/513c617cad408cd42725a6a5ee1d2fc3 to your computer and use it in GitHub Desktop.
SImple Have I Been Pwned API client in PowerShell. Check whether your passwords have been compromised.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Runs in PowerShell 5.1, PowerShell Core 6 on Windows and Linux, and PowerShell 7 preview | |
# Calculating SHA1 hash and returning it as a hexadecimal string | |
function Compute-SHA1Hash ([string] $string) { | |
$sha1 = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider | |
$encoder = New-Object System.Text.UTF8Encoding | |
$bytes = $encoder.GetBytes($string) | |
$hash = ($sha1.ComputeHash($bytes) | % { $_.ToString("X2") }) -join '' | |
return $hash | |
} | |
# Searching for compromised passwords per https://haveibeenpwned.com/API/v2#SearchingPwnedPasswordsByRange | |
# Returns number of known breaches containing the tested string: 0 means that the password seems okay so far; 3730471 means that your password is "password" | |
# Error handling is quite rudimentary, expand as you see fit. | |
function Get-PasswordPwnCount { | |
[CmdletBinding()] | |
param ([string] $pass) | |
$hash = Compute-SHA1Hash $pass | |
try { | |
$uri = "https://api.pwnedpasswords.com/range/$($hash.Substring(0,5))" | |
$list = -split (Invoke-RestMethod $uri -Verbose:($PSBoundParameters['Verbose'] -eq $true) -ErrorAction Stop) # split into separate strings | |
$pwn = $list | Select-String $hash.Substring(5,35) # grep | |
if ($pwn) { $count = [int] ($pwn.ToString().Split(':')[1]) } else { $count = 0 } | |
return $count | |
} | |
catch { | |
Write-Error "Error Calling HIBP API" | |
return $null | |
} | |
} | |
Get-PasswordPwnCount "AwesomePassword" | |
Get-PasswordPwnCount "AwesomerPassword" -Verbose |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment