Trying to create md5 hash of a string with powershell that matches linux-generated result... problem is of course that powershell seems to only hash files...
most answers point to memorystream/streamwriter... Posting this because there is an answer but have to search Powershell 2.0 to find so will post my own solution with link
CodePudding user response:
The post solves the problem... only found that after a need arose for legacy powershell 2.0 solution... simple search on powershell didn't turn up immediately (or my google-fu is lacking probably)... also, diff vs. linux (if i recall) is about UTF-8 mismatch...
Solution:
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = New-Object -TypeName System.Text.UTF8Encoding
$String = "Hello, world!"
$Hash = ([System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($String)))).replace("-","").ToLower()
CodePudding user response:
As you already noticed, there is no direct way or function to create a MD5 hash based on a string (without additional tools or modules for PS). However, you can use a MemoryStream to do it:
$stringAsStream = [System.IO.MemoryStream]::new()
$writer = [System.IO.StreamWriter]::new($stringAsStream)
$writer.write("MD5Online")
$writer.Flush()
$stringAsStream.Position = 0
Get-FileHash -InputStream $stringAsStream -Algorithm MD5
I've found this nice sample on https://infosecscout.com/get-md5-hash-in-powershell/ , which also contains further information about this topic.
If you want a simpler approach using PowerShell extensions, you can use the Get-Hash
cmdlet in the following module: https://github.com/Pscx/Pscx