Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create md5 hash in bash in Mac OS X

How can you create an md5 hash for a string on a mac using bash? md5sum does not exist in my environment. I did a man for md5 but I'm confused about what that really does.

md5 "string" 

does not return a hash.

like image 707
WildBill Avatar asked Jan 25 '12 01:01

WildBill


People also ask

How do I hash a file on a Mac?

You can easily check the MD5 Hash of any file on your Mac, all you need to do is launch the Terminal and type the 'md5' command and point it at the file you wish to check the md5 has for.


2 Answers

This should work -

[jaypal:~/Temp] echo "this will be encrypted" | md5 72caf9daf910b5ef86796f74c20b7e0b 

or if you prefer here string notation then -

[jaypal:~/Temp] md5 <<< 'this will be encrypted' 72caf9daf910b5ef86796f74c20b7e0b 

UPDATE:

Per the man page, you can play around with any of the following options

-s string         Print a checksum of the given string.  -p      Echo stdin to stdout and append the checksum to stdout.  -q      Quiet mode - only the checksum is printed out.  Overrides the -r option.   [jaypal:~/Temp] md5 -s 'this will be encrypted' MD5 ("this will be encrypted") = 502810f799de274ff7840a1549cd028a  [jaypal:~/Temp] md5 -qs 'this will be encrypted' 502810f799de274ff7840a1549cd028a 

Note: MD5 always produces the same hash. The reason you find the output different from the example given above is due to a point that has been made in the comments. The first two examples use the trailing newline character to produce the hash. To avoid that, you can use:

[jaypal:~/Temp] echo -n "this will be encrypted" | md5 502810f799de274ff7840a1549cd028a 

For example, if you use echo -n "string" | md5 (note the -n option), you get b45cffe084dd3d20d928bee85e7b0f21. But, if you use echo "string" | md5, you get b80fa55b1234f1935cea559d9efbc39a.

Or, verify it with the shell:

➜  [jaypal:~/Temp] [ $(echo "HOLA" | md5) = $(echo "HOLA" -n | md5) ]; echo "$?" 1 # 1 -> False. Hence, the result from echoing "HOLA" toggling the -n flag # outputs different md5 checksums. 
like image 167
jaypal singh Avatar answered Sep 21 '22 21:09

jaypal singh


To achieve what you asked:

md5 -s string 

outputs: MD5 ("string") = b45cffe084dd3d20d928bee85e7b0f21

like image 21
user3842869 Avatar answered Sep 21 '22 21:09

user3842869