December
19th,
2008
I’ve been recently working a lot with cryptographic hashes and sometimes it was useful to be able to check results or hash strings on my own while debugging or diagnosing something.
I started doing this so much, that ended up creating a few Windows PowerShell functions to deal with this:
function convert-tobinhex($array) {
$str = new-object system.text.stringbuilder
$array | %{
[void]$str.Append($_.ToString('x2'));
}
return $str.ToString()
}
function convert-frombinhex([string]$binhex) {
$arr = new-object byte[] ($binhex.Length/2)
for ( $i=0; $i -lt $arr.Length; $i++ ) {
$arr[$i] = [Convert]::ToByte($binhex.substring($i*2,2), 16)
}
return $arr
}
function get-hash($value, $hashalgo = 'MD5') {
$tohash = $value
if ( $value -is [string] ) {
$tohash = [text.encoding]::UTF8.GetBytes($value)
}
$hash = [security.cryptography.hashalgorithm]::Create($hashalgo)
return convert-tobinhex($hash.ComputeHash($tohash));
}
Not very efficient, but does the trick.