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
If I try and run your examples, it doesn’t work on MD5 or RIPEMD160, something about 1 argument?
You cannot call a method on a null-valued expression.
At C:\PowerShell\test2.ps1:5 char:1
+ [System.Security.Cryptography.HashAlgorithm]::Create($HashName).Compu …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Try renaming the functions they may be conflicting with the ones MS wrote.