2016-12-07 77 views
2

我需要計算Elixir中一個文件的md5總和,這怎麼能實現呢? 我期望是這樣的:如何計算Elixir中的文件校驗和?

iex(15)> {:ok, f} = File.open "file" 
{:ok, #PID<0.334.0>} 
iex(16)> :crypto.hash(:md5, f) 
** (ArgumentError) argument error 
      :erlang.iolist_to_binary(#PID<0.334.0>) 
    (crypto) crypto.erl:225: :crypto.hash/2 

但顯然它不工作..

Mix.Utils的文檔講述read_path功能link,但它並沒有任何工作。

iex(22)> Mix.Utils.read_path("file", [:sha512]) 
{:ok, "Elixir"} #the expected was {:checksum, "<checksum_value>"} 

是否有任何庫以簡單的方式提供此類功能?

+0

相關博文:http://www.cursingthedarkness.com/2015/04/how-to-get-hash-of-file-in-exilir.html –

回答

5

如果有人發現這個問題,並錯過@ FredtheMagicWonderDog的評論。 。 。

看看這個博客中:http://www.cursingthedarkness.com/2015/04/how-to-get-hash-of-file-in-exilir.html

而這裏的相關代碼:

File.stream!("./known_hosts.txt",[],2048) 
|> Enum.reduce(:crypto.hash_init(:sha256),fn(line, acc) -> :crypto.hash_update(acc,line) end) 
|> :crypto.hash_final 
|> Base.encode16 


#=> "97368E46417DF00CB833C73457D2BE0509C9A404B255D4C70BBDC792D248B4A2" 

NB:我張貼這是社會的維基。我並不想獲得代表點;只是爲了確保答案不在評論中。

2

我不知道長生不老藥,但在erlang本身,crypto:hash/2需要iodata,這是一個文件句柄不是。您需要讀取文件並將內容傳遞給hash()。如果你知道該文件相當小,{ok, Content} = file:read_file("file")(或相當於elixir)可以做到這一點。

1

這也是這項工作:

iex(25)> {:ok, content} = File.read "file" 
{:ok, "Elixir"} 
iex(26)> :crypto.hash(:md5, content) |> Base.encode16 
"A12EB062ECA9D1E6C69FCF8B603787C3" 

對同一文件的md5sum程序返回:

$ md5sum file 
a12eb062eca9d1e6c69fcf8b603787c3 file 

我用瑞恩提供的上述評論的信息,並增加了基礎。編碼16以達到最終結果。