Skip to content

Instantly share code, notes, and snippets.

@jrdmb
Last active February 11, 2020 21:50
Show Gist options
  • Save jrdmb/d38da10534a7a56af32d to your computer and use it in GitHub Desktop.
Save jrdmb/d38da10534a7a56af32d to your computer and use it in GitHub Desktop.
Hash a string in Powershell with various encryption algorithms
#Here is a simple script to hash a string using your chosen cryptography algorithm.
#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://jongurgul.com/blog/#Get-StringHash-get-filehash/
#https://gallery.technet.microsoft.com/scriptcenter/Get-StringHash-aa843f71
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()
}
$myvar = Read-Host –Prompt 'Enter string to hash using SHA-512 algorithm'
Get-StringHash $myvar "SHA512"
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
#PowerShell #encryption
@kl116004
Copy link

kl116004 commented Feb 26, 2018

$myvar = Read-Host –Prompt 'Enter string to hash using SHA-512 algorithm'$myvar

The dash before "Prompt" is an endash, script doesn't run. I get

At C:\Users\Nope\Powershell_String_Hashes.ps1:25 char:51
+ $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
+                                                   ~~
The string is missing the terminator: ".
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

Easy enough to fix in the editor, but figured you might want to know that, might be some weird encoding bug that the character was replaced at some point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment