Skip to content

Instantly share code, notes, and snippets.

@10nin
Created June 5, 2013 11:52
Show Gist options
  • Save 10nin/5713366 to your computer and use it in GitHub Desktop.
Save 10nin/5713366 to your computer and use it in GitHub Desktop.
Get MD5 message digest by elixir-lang.
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
@lstor
Copy link

lstor commented Apr 15, 2015

A few improvements:

  1. As @benjamintanweihao points out, bitstring_to_list and list_to_binary have been removed from Elixir.
  2. md5 is 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
end

@bheeshmar
Copy link

I 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

@jhonathas
Copy link

@bheeshmar ótima solução.

@zhangsoledad
Copy link

@bheeshmar awesome

@divmgl
Copy link

divmgl commented Apr 9, 2016

@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