bey*_*ran 7 haskell cryptography sha1
我有一个文件路径列表,并希望所有这些文件再次作为sha1编码的哈希存储在列表中.它应该尽可能通用,因此文件可以是文本也可以是二进制文件.现在我的问题是:
ham*_*mar 18
该cryptohash包可能是最简单的使用.只需将您的输入读入惰性1 ByteString并使用该hashlazy函数获取带有结果哈希的ByteString.这是一个小样本程序,您可以使用它来比较输出sha1sum.
import Crypto.Hash.SHA1 (hashlazy)
import qualified Data.ByteString as Strict
import qualified Data.ByteString.Lazy as Lazy
import System.Process (system)
import Text.Printf (printf)
hashFile :: FilePath -> IO Strict.ByteString
hashFile = fmap hashlazy . Lazy.readFile
toHex :: Strict.ByteString -> String
toHex bytes = Strict.unpack bytes >>= printf "%02x"
test :: FilePath -> IO ()
test path = do
hashFile path >>= putStrLn . toHex
system $ "sha1sum " ++ path
return ()
Run Code Online (Sandbox Code Playgroud)
因为它读取普通字节而不是字符,所以应该没有编码问题,它应该总是给出相同的结果sha1sum:
> test "/usr/share/dict/words"
d6e483cb67d6de3b8cfe8f4952eb55453bb99116
d6e483cb67d6de3b8cfe8f4952eb55453bb99116 /usr/share/dict/words
Run Code Online (Sandbox Code Playgroud)
这也适用于cryptohash包支持的任何哈希.只需将导入更改为例如Crypto.Hash.SHA256使用不同的哈希.
1使用lazy ByteStrings可以避免一次将整个文件加载到内存中,这在处理大文件时很重要.