簡體   English   中英

如何計算 Elixir 中的文件校驗和?

[英]How can I calculate a file checksum in Elixir?

我需要計算Elixir中一個文件的md5和,這怎么實現呢? 我希望是這樣的:

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/2 ,但它也不起作用。

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

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

萬一其他人發現這個問題並錯過了@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" 

注意:我將此作為社區維基發布。 我不是想獲得代表積分; 只是想確保答案不會隱藏在評論中。

這也可以完成工作:

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

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

$ md5sum file 
a12eb062eca9d1e6c69fcf8b603787c3  file

我使用了上面評論中 Ryan 提供的信息,並添加了 Base.encode16 以達到最終結果。

我不知道長生不老葯,但在 erlang 中, crypto:hash/2采用 iodata,而文件句柄不是。 您需要讀取文件並將內容傳遞給 hash()。 如果您知道文件相當小,那么{ok, Content} = file:read_file("file") (或等效的 elixir)可以解決問題。

除了@aeliton 解決方案短小精悍之外,它還具有最佳性能。

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM