:-6ren">
gpt4 book ai didi

functional-programming - 如何在 Elixir 中计算文件校验和?

转载 作者:行者123 更新时间:2023-12-04 08:43:08 25 4
gpt4 key购买 nike

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

注意:我将此作为社区维基发布。我不是想获得代表积分;只是想确保答案不会隐藏在评论中。

关于functional-programming - 如何在 Elixir 中计算文件校验和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41008487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com