【问题标题】:How can I calculate a file checksum in Elixir?如何在 Elixir 中计算文件校验和?
【发布时间】:2017-04-21 20:48:12
【问题描述】:

我需要在 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>"}

是否有任何库可以简单地提供此类功能?

【问题讨论】:

标签: functional-programming erlang elixir md5 checksum


【解决方案1】:

万一其他人发现这个问题并错过了@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" 

注意:我将其发布为社区 wiki。我不是想获得代表点数;只是试图确保答案不会隐藏在 cmets 中。

【讨论】:

    【解决方案2】:

    这也能起到作用:

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

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

    $ md5sum file 
    a12eb062eca9d1e6c69fcf8b603787c3  file
    

    我已经使用了上面cmets中Ryan提供的信息,并添加了Base.encode16以达到最终结果。

    【讨论】:

      【解决方案3】:

      我不知道 elixir,但在 erlang 中,crypto:hash/2 使用 iodata,而文件句柄不是。您需要读取文件并将内容传递给 hash()。如果您知道该文件相当小,{ok, Content} = file:read_file("file")(或等效的长生不老药)可以解决问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-03
        • 2012-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多