An MD5 hash for any given message is 16 bytes (128 bits) in size and is represented by a unique 32 digit Hexadecimal number.
Erlang has a built-in-function to calculate the MD5, which returns the hash in the form of a binary data-structure.
$ erlang:md5("hello"). <93,65,64,42,188,75,42,118,185,113,157,145,16,23,197,146>
But what we usually need is a string representation of the Hexadecimal value. Hence, we need to convert the Erlang Binary to a Hex-string, for which I didn’t find any BIF.
So first of all, lets convert the Binary to a list (of integers)- so that we can process it easily. Erlang has a function for converting binary to list:
$ binary_to_list(<93,65,64,42,188,75,42,118,185,113,157,145,16,23,197,146>). [93,65,64,42,188,75,42,118,185,113,157,145,16,23,197,146]
Now, we have to convert each of the integers in the list into its hex equivalent. How do you convert an integer in Decimal system to a Hexadecimal system?
Eg. Take an integer 230. Divide it by 16.
230 div 16 = 14 In Hex, 14 is E
230 rem 16 = 6 In Hex, 6 is 6
So 230 in Hex is E6.
Now we will have to do the same for every integer in the list. I did it using the lists:map function and the applying the int_to_hex conversion to every integer:
$ lists:map(fun(X) -> int_to_hex(X) end, L).
This will actually return a list of integers representing the (hex) string, which is how a string is represented in Erlang – a list of Integers.
The complete code is below:
-module(md5). -export([md5_hex/1]). md5_hex(S) -> Md5_bin = erlang:md5(S), Md5_list = binary_to_list(Md5_bin), lists:flatten(list_to_hex(Md5_list)). list_to_hex(L) -> lists:map(fun(X) -> int_to_hex(X) end, L). int_to_hex(N) when N < 256 -> [hex(N div 16), hex(N rem 16)]. hex(N) when N < 10 -> $0+N; hex(N) when N >= 10, N < 16 -> $a + (N-10).
$ md5:md5_hex("hello"). "5d41402abc4b2a76b9719d911017c592"