Last active
April 2, 2021 19:14
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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