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


Comments

6 responses to “Get-StringHash and Get-FileHash”

  1. Thanks for the handy functions! I use them in a helper script for a Chocolatey package.

    1. Glad you found it useful

  2. […] assigned to the resource has to be globally unique, we’ll make use of a function written by Jon Gurgul which takes a string (which in this case will be the resource ID of the Azure Resource Group we […]

  3. […] To generate a hash of the password we are entering, we’re using Get-StringHash made by Jon Gurgul. To find the get-stringhash function you can visit the PowerShell gallery here or read Jon’s blog about it here […]

Leave a Reply

Your email address will not be published. Required fields are marked *