Compute MD5 digest of file in Haskell

柔情痞子 提交于 2019-12-07 03:50:25

问题


Using Haskell, how can I compute the MD5 digest of a file without using external tools like md5sum?

Note: This question intentionally shows no effort as I answered it right away.


回答1:


One option is to use the pureMD5 package, for example if you want to compute the hash of the file foo.txt:

import qualified Data.ByteString.Lazy as LB
import Data.Digest.Pure.MD5

main :: IO ()
main = do
    fileContent <- LB.readFile "foo.txt"
    let md5Digest = md5 fileContent
    print md5Digest

This code prints the the same MD5 sum as md5sum foo.txt.

If you prefer a one-liner, you can use this one (the imports are the same as above):

LB.readFile "foo.txt" >>= print . md5



回答2:


Another option would be using cryptohash which is based on a C implementation and also provides other hashes algorithms like SHA1:

import qualified Data.ByteString.Lazy as LB
import Crypto.Hash

md5 :: LB.ByteString -> Digest MD5
md5 = hashlazy

main :: IO ()
main = do
    fileContent <- LB.readFile "foo.txt"
    let md5Digest = md5 fileContent
    print $ digestToHexByteString md5Digest


来源:https://stackoverflow.com/questions/30536583/compute-md5-digest-of-file-in-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!