Skip to content

Instantly share code, notes, and snippets.

@jrotello
Last active April 2, 2021 19:14
Show Gist options
  • Save jrotello/327d28b82ee47b7830396dbd1c8c5a8a to your computer and use it in GitHub Desktop.
Save jrotello/327d28b82ee47b7830396dbd1c8c5a8a to your computer and use it in GitHub Desktop.
PowerShell function to compute hashes of string values. Use built-in Get-FileHash for hashing the contents of files.
function Get-Hash {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline)]
[string]$Value,
[Parameter()]
[ValidateSet('sha1', 'sha256', 'sha384', 'sha512', 'md5')]
[string]$Algorithm = 'sha256',
[Parameter()]
[ValidateSet('hex', 'base64')]
[string]$Format = 'hex'
)
$hasher = [System.Security.Cryptography.HashAlgorithm]::Create($Algorithm)
$bytes = $hasher.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($Value))
switch ($Format) {
"hex" {
[System.BitConverter]::ToString($bytes).Replace('-', '').ToLowerInvariant()
}
"base64" {
[System.Convert]::ToBase64String($bytes)
}
Default {
[System.BitConverter]::ToString($bytes).Replace('-', '').ToLowerInvariant()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment