PowerShell : Getting the hash value for a string
A simple yet often useful scripting task is getting the hash value for a string. Since I recently wrote this very short function for my colleague Laurent Banon (blog) allow me to share it with you.
function Hash($textToHash)
{
$hasher = new-object System.Security.Cryptography.SHA256Managed
$toHash = [System.Text.Encoding]::UTF8.GetBytes($textToHash)
$hashByteArray = $hasher.ComputeHash($toHash)
foreach($byte in $hashByteArray)
{
$res += $byte.ToString()
}
return $res;
}
And its usage :
PS #> . Hash.ps1
PS #> Hash("hi")
Instead of SHA256, you can use other hashing algorithms like the ones available by default in .NET 3.5 ou 4 :
- System.Security.Cryptography.MD5
- System.Security.Cryptography.RIPEMD160
- System.Security.Cryptography.SHA1
- System.Security.Cryptography.SHA256
- System.Security.Cryptography.SHA384
- System.Security.Cryptography.SHA512
Happy scripting!
Comments
Anonymous
April 25, 2011
The comment has been removedAnonymous
April 27, 2011
This is not possible unless the algorithm you use is a perfect hashing function (i.e. no collision), which is a very particular case scenario. You will generally want to use hashes for passwords or for indexing. en.wikipedia.org/.../Hash_functionAnonymous
November 18, 2013
The comment has been removedAnonymous
September 25, 2014
Loop it seem to be like this $res = "" foreach($byte in $hash) { $res += [System.String]::Format("{0:X2}", $byte) } $resAnonymous
April 22, 2015
The comment has been removedAnonymous
September 24, 2015
would "Simply".GetHashCode() be ok