Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PHP's md5 is different from OpenSSL's md5?

Tags:

php

openssl

md5

I am quite confused as to why I am seeing different results for md5 hashing in PHP and in OpenSSL.

Here is the code that I am running:

php -r "echo md5('abc');"

Results in: 900150983cd24fb0d6963f7d28e17f72

While this:

echo abc | openssl md5

Results in: 0bee89b07a248e27c83fc3d5951213c1

Why?

like image 832
Alex N. Avatar asked Jul 02 '10 23:07

Alex N.


2 Answers

There is only one way to compute MD5.

A blind guess is that the second one also includes a newline inside the string being hashed.

Yeh, verified it. That's it.

like image 189
jdehaan Avatar answered Sep 20 '22 23:09

jdehaan


As everyone noted, the problem is that echo prints an extra newline.

However, the solution proposed (echo -n) is not completely correct. According to the POSIX standard, "Implementations shall not support any options." You'll make the world a bit better if you don't use it. Use

printf %s abc | openssl md5

or simply

printf abc | openssl md5
like image 21
Roman Cheplyaka Avatar answered Sep 17 '22 23:09

Roman Cheplyaka