Monday, May 28, 2012

Windows Command Line Hash Check

Knowing that, "Linux has been doing this for years" I decided to add make a command line method for checking the MD5 and SHA hashes of downloaded files. I used PowerShell to create a function and added it to my profile so that I can call it whenever I want. First, the code for the function:


function Check-Hash {
param
(
 $file,
 [switch]$SHA1 = $false,
 [switch]$SHA256 = $false,
 [switch]$MD5 = $false
)

function computeHash {
$stream = New-Object System.IO.FileStream($file, [System.IO.FileMode]::Open)
$stringBuilder = New-Object System.Text.StringBuilder
$hash = $algo.ComputeHash($stream) | % { [void] $stringBuilder.Append($_.ToString("x2")) }
$stringBuilder.ToString()
$stream.Dispose()
}

if ($SHA1) {
  $algo = New-Object System.Security.Cryptography.SHA1Managed
  Write-Host "SHA1: " -NoNewline ; computeHash
 }
if  ($SHA256) {
  $algo = New-Object System.Security.Cryptography.SHA256Managed
  Write-Host "SHA256: " -NoNewline ; computeHash
 }
if ($MD5) {
  $algo = New-Object System.Security.Cryptography.MD5CryptoServiceProvider
  Write-Host "MD5: " -NoNewline ; computeHash
 }

}
You can save this as Check-Hash.ps1, which matches the function name. Next, you can add the path to the .ps1 file to your profile, so that when you start up PowerShell, you'll have this function by default. The link to edit your profile can be found here:

http://msdn.microsoft.com/en-us/library/windows/desktop/bb613488(v=vs.85).aspx

Once added, you can check the hash of a file you downloaded, using any combination of the algorithms. The syntax is, "Check-Hash -filename -SHA1 -SHA256 -MD5". Here is an example of a download and it's matching hash:


No comments:

Post a Comment