As a follow up to yesterday’s how-to, I thought hashing might a thing to cover.  We use hashes all the time, but it’s annoying that md5sum, sha1sum and sha256sum aren’t part of the windows command set – or are they?  Yup, it turns out that they most definitely are part of PowerShell:

Get-FileHash -path $filename -Algorithm $algo

Where the Algorithm is a string, any one of:
“SHA1″,”SHA256″,”SHA384″,”SHA512″,”MACTripleDES”,”MD5″,”RIPEMD160″

$a = get-filehash -Path .somefile.txt -Algorithm SHA256

$a

Algorithm       Hash                                                                   Path
———       —-                                                                   —-
SHA256          0ACDA2996D999257BD8E4EE7AD43065626A14105A06DC00973959F9B032DE0E9       somefile.txt

$a.Hash
0ACDA2996D999257BD8E4EE7AD43065626A14105A06DC00973959F9B032DE0E9

But what about string values?  If you want to hash a string, there doesn’t seem to be a function for that.  It turns out that while it’s not part of PowerShell as a separate thing, it’s pretty easy to access it using the string as an “inputstring” variable:

$stringAsStream = [System.IO.MemoryStream]::new()

$writer = [System.IO.StreamWriter]::new($stringAsStream)

$writer.write(“RADIO CHECK”)

$writer.Flush()

$stringAsStream.Position = 0

Get-FileHash -Algorithm “SHA256” -InputStream $stringAsStream | Select-Object Hash

Hash

—-

A450215BE7B1BC6006D41FF62A9324FEB4CD6D194462CB119391CE21555658BB

So, this gets the job done but it’s a bit cludgy, let’s drop it into a function, then call the function:

function Get-StringHash ( [String] $InputString, $HashAlgo)

    {

    $stringAsStream = [System.IO.MemoryStream]::new()

    $writer = [System.IO.StreamWriter]::new($stringAsStream)

    $writer.write($InputString)

    $writer.Flush()

    $stringAsStream.Position = 0

    Get-FileHash -Algorithm $HashAlgo -InputStream $stringAsStream | Select-Object Hash

    }

$a =  get-stringhash “LOUD AND CLEAR” “SHA256”

$a

Hash

—-

7FE22308D7B971EDCADB8963188E46220E9D5778671C256216AEA712A33D4A3E

$a.Hash

7FE22308D7B971EDCADB8963188E46220E9D5778671C256216AEA712A33D4A3E

This “common infosec functions in PowerShell” thing kinda got started by accident, and got extended when Jim Clausing asked me if I was going to re-write CyberChef in PowerShell?.  Of course my answer was “If you’re going to put down a dare like that, challenge accepted” – so look for more stories of this type in future.  As I introduce more functions, I’ll roll them into the same GUI as I presented yesterday, code will get updated in my github ( https://github.com/robvandenbrink ).

===============
Rob VandenBrink
www.coherentsecurity.com

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.