Get-StringHash and Get-FileHash

Hashing

Here are two of my powershell scripts that provide a quick and easy way to hash either a string or a file using any of the cryptography hash algorithms.

Get-StringHash

#http://jongurgul.com/blog/get-stringhash-get-filehash/
Function Get-StringHash([String] $String,$HashName = "MD5")
{
$StringBuilder = New-Object System.Text.StringBuilder
[System.Security.Cryptography.HashAlgorithm]::Create($HashName).ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String))|%{
[Void]$StringBuilder.Append($_.ToString("x2"))
}
$StringBuilder.ToString()
}

Usage Examples:

Get-StringHash “My String to hash” “MD5”
Get-StringHash “My String to hash” “RIPEMD160”
Get-StringHash “My String to hash” “SHA1”
Get-StringHash “My String to hash” “SHA256”
Get-StringHash “My String to hash” “SHA384”
Get-StringHash “My String to hash” “SHA512”

http://gallery.technet.microsoft.com/scriptcenter/Get-StringHash-aa843f71

Get-FileHash

#http://jongurgul.com/blog/get-stringhash-get-filehash/
Function Get-FileHash([String] $FileName,$HashName = "MD5")
{
$FileStream = New-Object System.IO.FileStream($FileName,[System.IO.FileMode]::Open)
$StringBuilder = New-Object System.Text.StringBuilder
[System.Security.Cryptography.HashAlgorithm]::Create($HashName).ComputeHash($FileStream)|%{[Void]$StringBuilder.Append($_.ToString("x2"))}
$FileStream.Close()
$FileStream.Dispose()
$StringBuilder.ToString()
}

Usage Examples:

Get-FileHash “C:\MyFile.txt” “MD5”
Get-FileHash “C:\MyFile.txt” “RIPEMD160”
Get-FileHash “C:\MyFile.txt” “SHA1”
Get-FileHash “C:\MyFile.txt” “SHA256”
Get-FileHash “C:\MyFile.txt” “SHA384”
Get-FileHash “C:\MyFile.txt” “SHA512”

http://gallery.technet.microsoft.com/scriptcenter/Get-FileHash-83ab0189

3 Replies to “Get-StringHash and Get-FileHash”

Leave a Reply