Skip to content

Instantly share code, notes, and snippets.

@MultiversalNomad
Last active November 13, 2020 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MultiversalNomad/7b385d30ecfb3eebf8cfae43f331da2d to your computer and use it in GitHub Desktop.
Save MultiversalNomad/7b385d30ecfb3eebf8cfae43f331da2d to your computer and use it in GitHub Desktop.
A helpful PowerShell script for quickly comparing 2 hashes to see if they match or not. See code comments for details.
<#
A helpful PowerShell script for quickly comparing 2 hashes to see if they match or not.
Requires Windows 10 at a minimum since it uses the built-in "certutil" tool to generate hashes.
The script takes 3 inputs: source, target, and hash type.
The "source" and "target" inputs can either be full filepaths for the files being hashed or they
can be actual hash strings (for example, both can be filepaths, or both can be hash strings, or
one can be a filepath with the other being a hash string).
The "hash type" input is used to tell certutil what kind of hash to use (e.g., MD5, SHA256, etc.).
#>
function Write-This-Many-Lines($lines, $num)
{
if ($num -le $lines.count)
{
for ($i = 0; $i -lt $num; $i++)
{
Write-Output $lines[$i]
}
}
}
function Get-Hash($given_value, $hash_type)
{
$hash = $given_value
if (Test-Path -Path $given_value)
{
$hash_type = $hash_type.Trim()
$hash_type = $hash_type.Replace(" ", "")
$hash_type = $hash_type.Replace("-", "")
$output_lines = certutil "-hashfile" $given_value $hash_type
Write-This-Many-Lines $output_lines 2
if ($output_lines.length -gt 0)
{
$hash = $output_lines[1]
}
}
else
{
Write-Output $hash
}
$hash = $hash.ToLower()
$hash = $hash.Trim()
$hash = $hash.Replace(" ", "")
Write-Output "Hash converted to lowercase with whitespace removed:"
Write-Output $hash
}
function Write-Last-Line($lines)
{
if ($lines.count -le 1)
{
$value = $lines
}
else
{
$value = $lines[$lines.count - 1]
}
Write-Output $value
}
function Compare-Hashes($source, $target, $hash_type)
{
if (-not ($source))
{
$source = ""
}
if (-not ($target))
{
$target = ""
}
if (-not ($hash_type))
{
$hash_type = ""
}
$output_lines = Get-Hash $source $hash_type
Write-Output $output_lines
$source_hash = Write-Last-Line $output_lines
$output_lines = Get-Hash $target $hash_type
Write-Output $output_lines
$target_hash = Write-Last-Line $output_lines
if ($source_hash -ne "" -and $source_hash -notlike "CertUtil:*"`
-and $target_hash -ne "" -and $target_hash -notlike "CertUtil:*")
{
if ($source_hash -eq $target_hash)
{
Write-Output "Hashes are the same."
}
else
{
Write-Output "Hashes are different."
}
}
else
{
Write-Output "Hash not generated for at least one of the files or at least one of the supplied hashes is an empty string."
}
}
Compare-Hashes $Args[0] $Args[1] $Args[2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment