Skip to content

Instantly share code, notes, and snippets.

@maravedi
Created September 7, 2019 18:54
Show Gist options
  • Save maravedi/724efde689a1f116d81f5e9d1ad5d2a5 to your computer and use it in GitHub Desktop.
Save maravedi/724efde689a1f116d81f5e9d1ad5d2a5 to your computer and use it in GitHub Desktop.
PowerShell String-hashing Function
# This is a customized version of the work done by jermity: https://gist.github.com/jermity/d38da10534a7a56af32d
# Examples:
# To List all available algorithms:
# Get-StringHash -List
#
# To hash the string using all available algorithms:
# 'test' | Get-StringHash -All
#
# To do the same as above, but without using the pipeline:
# Get-StringHash -String 'test' -All
#
# To hash the string using a specific algorithm:
# 'test' | Get-StringHash -HashName SHA1
#
# To do the same as above, but without using the pipeline:
# Get-StringHash -HashName SHA1 -String 'test'
Function Get-StringHash{
[CmdletBinding()]
Param(
[Parameter(ValueFromPipeline = $True)]
[String]$String,
$HashName = "MD5",
[Switch]$List,
[Switch]$All
)
$Algorithms = @('MD5', 'SHA1', 'SHA256', 'SHA384', 'SHA512')
If($List){
Write-Host "Algorithms available: $($Algorithms -Join ', ')"
return
} ElseIf($All) {
$Array = @{}
Foreach($Algorithm in $Algorithms) {
$Row = "" | Select Algorithm, Hash
$StringBuilder = New-Object System.Text.StringBuilder
[System.Security.Cryptography.HashAlgorithm]::Create($Algorithm).ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String))|%{
[Void]$StringBuilder.Append($_.ToString("x2"))
}
$Row.Algorithm = $Algorithm
$Row.Hash = $StringBuilder.ToString()
$Array.Add($Row.Algorithm, $Row.Hash)
}
return $Array.Keys | Select @{N='Algorithm';E={$_}},@{N='Hash';E={$Array.$_}}
} Else {
$StringBuilder = New-Object System.Text.StringBuilder
[System.Security.Cryptography.HashAlgorithm]::Create($HashName).ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String))|%{
[Void]$StringBuilder.Append($_.ToString("x2"))
}
return $StringBuilder.ToString()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment