md5sum vs md5 – different algorithms?

Calculate md5 hash with md5sum, php, python and perl oneliners:

$ echo "hello" | md5sum 
b1946ac92492d2347c6235b4d2611184  -
$ php -r "echo md5('hello');"
5d41402abc4b2a76b9719d911017c592
$ python -c "import hashlib; print hashlib.md5('hello').hexdigest();"
5d41402abc4b2a76b9719d911017c592
$ perl -MDigest::MD5=md5_hex -e 'print md5_hex("hello") . "\n";'
5d41402abc4b2a76b9719d911017c592

And here will you have question – is md5sum (part of sys-apps/coreutils if you are using Gentoo) using some other algorithm to compute hash? Answer is no! It uses same algorithm, and problem lies not in md5sum itself but in echo.

Echo enters linebreak at the end of string. There is two solutions with echo command

$ echo -n "hello" | md5sum 
5d41402abc4b2a76b9719d911017c592  -
$ echo -e "hello\c" | md5sum 
5d41402abc4b2a76b9719d911017c592  -

In first case there is used parameter -n which says to echo – do not output the trailing newline.
In second case -e forces echo to accept backslash characters and \c ends output.

.. or use some other command to output string:

$ printf "hello" | md5sum 
5d41402abc4b2a76b9719d911017c592  -

.. or use md5sum in “read in” mode (after you have written ‘hello’ press Ctrl+D twice):

$ md5sum -t 
hello5d41402abc4b2a76b9719d911017c592  -

.. or write string into a file without linebreak:

$ md5sum password_file
This entry was posted in Uncategorized. Bookmark the permalink.

3 Responses to md5sum vs md5 – different algorithms?

  1. chaosinux says:

    Thanks, I encountered the same problem, 🙂

  2. William Jimenez says:

    thanks for the detailed explanation!

  3. Oh my. I’m blushing now. Years and years trying to figure out why there were apparently ‘different’ MD5 algorithms, and it was ‘only’ a problem with echo and nothing more… I feel ashamed of myself for never having thought about something that simple!!

    Thank you so much — you made my day!

Leave a Reply

Your email address will not be published. Required fields are marked *

Exaptcha (all lowercase letters) reload *