Monday, June 29, 2009

PowerShell: MD5/SHA1 hashes of files

Problem Statement: I need to get Signatures (MD5 and SHA1) of all the files present at a certain location on the hard disk.
Utility: This could be for checking the signature of the files present in the downloaded build for correctness or if need be for whitelisting of files.
Here's a small PowerShell script

function Get-Md5{
param ($file)
$input = get-content -encoding byte -readcount -1 $file$md5 = [System.Security.Cryptography.MD5]::Create()
$output = $md5.ComputeHash($input)$sb = new-object Text.StringBuilder
foreach ($b in $output) {
[void] $sb.Append($b.ToString("X2"));
}
$sb.ToString()
}function Get-SHA1{param ($file)
$input = get-content -encoding byte -readcount -1 $file$sha1 = [System.Security.Cryptography.SHA1]::Create()
$output = $sha1.ComputeHash($input)
$sb = new-object Text.StringBuilder
foreach ($b in $output) {
[void] $sb.Append($b.ToString("X2"));
}
$sb.ToString()
}
"MD5`tSHA1`tFilePath" out-file C:\Hashes.xls -append$files = get-childitem $args -recurse -include *.*
foreach ($i in $files) {
$md5 = get-md5 $i $sha1 = get-sha1 $i "$md5`t$sha1`t$i" out-file C:\Hashes.xls -append
}
Hope this helps.

No comments: