Tuesday, September 08, 2015

md5 checksum in powershell

It seems I have been stuck in Windows recently. The main annoyance with that is it loves to fight me and hates to tell me what is going on. As a result, sometimes I need to write my own tools. And, yes, they do tend to emulate what I have used in Linux. Take for example md5sum, an example of a command that just happens to be related to the topic of this article.

Here is how md5sum works in Linux:

raub@desktop:~$ md5sum disallowedcert.sst
6e8bf95470e7f1ca0626012ea21e55f7 disallowedcert.sst
raub@desktop:~$

As the man page tells us, there are other options we can use. But, I do not use most of them. So, how about if we write a quick powershell script to emulate at least the basic usage of md5sum?

Warning

The md5 should not be used for, say, verify integrity of a file if you care about security; the MD5 algorithm can be hacked using collision attacks.

The code

Here is a first shot at the code

# emulate md5sum in powershell
foreach ($file in $args)
{
   $md5 = New-Object -typeName `
          System.Security.Cryptography.MD5CryptoServiceProvider
   $hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($file)))
   echo "$hash $file"
}
PS C:\Users\User\test> powershell -executionpolicy bypass -file .\md5.ps1 .\disallowedcert.sst
6E-8B-F9-54-70-E7-F1-CA-06-26-01-2E-A2-1E-55-F7
PS C:\Users\User\test> powershell -executionpolicy bypass -file .\md5.ps1 .\disallowedcert.sst .\e098
cf355c19953274d84772a1cec96dc3356ca.crt
6E-8B-F9-54-70-E7-F1-CA-06-26-01-2E-A2-1E-55-F7
1C-BC-A2-83-77-BA-25-04-3D-6D-42-6E-E2-11-34-55
PS C:\Users\User\test>

Let's improve on it a bit then

# emulate md5sum in powershell
foreach ($file in $args)
{
   $md5 = New-Object -typeName `
          System.Security.Cryptography.MD5CryptoServiceProvider
   $hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($file))) `
           -replace "-",""
   echo "$hash $file"
}

Let's try it out

PS C:\Users\User\test> powershell -executionpolicy bypass -file md5.ps1 md5sum.ps1 ntpTime.ps1 
F1930269F287A434993172A362269F8E md5sum.ps1
FC6ED0787947524543D34CFBA3BE641A ntpTime.ps1

PS C:\Users\User\test> 

That's much more like it.

Other versions

If you do not like my script there are a few versions out there you can download and run instead. Pick your poison!

No comments: