Reputation: 388
I'm using a very simple Powershell function to compute an MD5 hash
$someString = "Hello World!"
$md5 = new-object -TypeNameSystem.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = new-object -TypeName System.Text.UTF8Encoding
$bithash = [System.BitConverter]::ToString($md5.ComputeHash(($utf8.GetBytes($someString))))
$hash = [convert]::tostring($bitHash,16)
Write-Host $hash
According to the MSDN page, System.BitConverter to return a hexadecimal representation which I then try to convert into a string
The code above returns an error that the input for toString is not the correct format.
What am I missing here?
I am looking to make an MD5 function in powershell that matches output of http://md5.gromweb.com/
Upvotes: 2
Views: 4775
Reputation: 47872
If you're using PowerShell 4, here's an alternative way:
$stream = New-Object System.IO.MemoryStream -ArgumentList @(,$utf8.GetBytes($someString))
$hash = Get-FileHash -Algorithm MD5 -InputStream $stream | Select-Object -ExpandProperty Hash
In PowerShell 5+:
$stream = [System.IO.MemoryStream]::new($utf8.GetBytes($someString))
$hash = Get-FileHash -Algorithm MD5 -InputStream $stream | Select-Object -ExpandProperty Hash
Upvotes: 2