Haskell中的SHA1编码

栏目: 编程语言 · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/9502777/sha1-encoding-in-haskell
我有一个文件路径列表,并希望所有这些文件再次作为sha1编码的哈希存储在列表中.它应该尽可能通用,因此文件可以是文本也可以是二进制文件.现在我的问题是:

>应该使用哪些包?为什么?

>方法的一致性如何?我的意思是:如果使用sha1编码自身的不同程序可能会有不同的结果(例如sha1sum)

cryptohash

软件包可能是最简单的使用方法.只需将您的输入读入lazy1 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 ()

因为它读取普通字节而不是字符,所以应该没有编码问题,它应该总是给出与sha1sum相同的结果:

> test "/usr/share/dict/words"
d6e483cb67d6de3b8cfe8f4952eb55453bb99116
d6e483cb67d6de3b8cfe8f4952eb55453bb99116  /usr/share/dict/words

这也适用于cryptohash包支持的任何哈希.只需将导入更改为例如Crypto.Hash.SHA256使用不同的哈希.

1使用lazy ByteStrings可以避免一次将整个文件加载到内存中,这在处理大文件时很重要.

翻译自:https://stackoverflow.com/questions/9502777/sha1-encoding-in-haskell


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms Unlocked

Algorithms Unlocked

Thomas H. Cormen / The MIT Press / 2013-3-1 / USD 25.00

Have you ever wondered how your GPS can find the fastest way to your destination, selecting one route from seemingly countless possibilities in mere seconds? How your credit card account number is pro......一起来看看 《Algorithms Unlocked》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具