Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and bash return different hash results

Tags:

bash

php

hash

I'm getting different results when trying to generate a hash using bash commands and PHP's hash() function. I looked at previous questions and the most common problem is that there's a new line or some other character hiding within the string, however I'm running the functions on actual strings and not files so this isn't the problem.

For example:

Bash:

md5sum <<< hello : b1946ac92492d2347c6235b4d2611184

sha256sum <<< hello : 5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03

PHP's hash() function:

hash('md5', 'hello') : 9dd4e461268c8034f5c8564e155c67a6

hash('sha256', 'hello') : 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

What am I missing here? Why are the values different?

like image 768
mittelmania Avatar asked Feb 11 '23 23:02

mittelmania


1 Answers

Because md5sum append a newline character to your input before hashing it

The PHP equivalent is:

echo hash('md5', "hello\n");

which will generate b1946ac92492d2347c6235b4d2611184, the same value as

md5sum <<< hello

If you want to suppress the newline from being included in a bash-generated hash, use

echo -n hello | md5sum 
like image 148
Mark Baker Avatar answered Feb 21 '23 04:02

Mark Baker