Created
June 5, 2013 11:52
-
-
Save 10nin/5713366 to your computer and use it in GitHub Desktop.
Get MD5 message digest by elixir-lang.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| defmodule Crypto do | |
| def md5(s) do | |
| list_to_binary(Enum.map(bitstring_to_list(:crypto.md5(s)), fn(x) -> integer_to_binary(x, 16) end)) | |
| end | |
| end |
It has an bug, because integer_to_binary/2 will trim the 0 in front of an number, like integer_to_binary(02, 16) -> "2" in this case, the caculated md5 length will be decreased. I write an little sample:
def md5(s) do
:crypto.hash(:md5, s)
|> bitstring_to_list
|> Enum.map(&(:io_lib.format("~2.16.0b", [&1])))
|> List.flatten
|> list_to_bitstring
end
A few improvements:
- As @benjamintanweihao points out,
bitstring_to_listandlist_to_binaryhave been removed from Elixir. md5is a top-level function in Erlang, so you can call it simply as:erlang.md5(s).
defmodule Crypto do
def md5(data) do
:erlang.md5(data)
|> :erlang.bitstring_to_list
|> Enum.map(&(:io_lib.format("~2.16.0b", [&1])))
|> List.flatten
|> :erlang.list_to_bitstring
end
endI found a clearer way to encode the bitstring: Base.encode16
defmodule Crypto do
def md5(data) do
Base.encode16(:erlang.md5(data), case: :lower)
end
end@bheeshmar ótima solução.
@bheeshmar awesome
@bheeshmar you win the internet. thanks for this
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this! Saved me a bunch of time. The list to binary should probably be :erlang.list_to_binary as it's removed from Elixir.