试图在 Haskell 中将随机字符串传递给 SHA

Trying to pass a random string to SHA in Haskell

我正在尝试将一个随机字符串(恰好是一个数字)“4176730.5”传递给 Haskell 中的 SHA,以获得更大的随机字符串,例如“2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881”。

我有这段代码可以生成随机数并将其转换为字符串

  num <- randomIO :: IO Float

  let x = C.pack (show (num*10000000))

  print x

但是当我用

将它传递给 SHA 时
  let a = sha256 x

我收到错误

Couldn't match expected type ‘Data.ByteString.Lazy.Internal.ByteString’
            with actual type ‘C.ByteString’

我试过将我的数字转换为 C.ByteString,但根据 Haskell 编译器,我认为有两种类型的字节串。

完整代码为:

import Data.Digest.Pure.SHA
import System.Random
import qualified Data.ByteString.Char8 as C

main :: IO ()

main = do
  num <- randomIO :: IO Float

  let x = C.pack (show (num*10000000))

  print x

  let a = sha256 x

      b = hmacSha256 "key" "some test message"
  mapM_ print [showDigest a, showDigest b]

显然有两种类型的 Bytestring,而我投错了一种,如何正确投射我的随机字符串?

如果我替换了下面@Cubic 的回答 将合格的 Data.ByteString.Char8 导入为 C

import qualified Data.ByteString.Lazy as C

我刚收到这些错误

Couldn't match type ‘Char’ with ‘GHC.Word.Word8’
Expected type: [GHC.Word.Word8]
  Actual type: String

Couldn't match expected type ‘C.ByteString’
            with actual type ‘[Char]’

您需要 Data.ByteString.Lazy,而不是 Data.ByteString.Char8

一般来说,您几乎从不需要 Data.ByteString.Char8

只需使用@leftaroundabout 提到的惰性字节串。你的尝试没有成功,因为你想从字符串中打包,所以你需要导入 .Char8 模块来实现:

import Data.ByteString.Lazy.Char8 as C

问题是 ByteString 是字节序列,而 String 是字符序列。有很多方法可以将字符转换为字节,因此您需要指定您想要的编码方式。您很可能需要 ASCII 或 UTF8 编码。如果是这样,您可以使用下面的解决方案,它根据需要将字符串转换为 "UTF8 bytes"。

import Data.Digest.Pure.SHA
import System.Random
import qualified Data.ByteString.Lazy as C
import qualified Data.ByteString.Lazy.UTF8 as U

main :: IO ()

main = do
  num <- randomIO :: IO Float

  let x = U.fromString (show (num*10000000))

  print x

  let a = sha256 x

      b = hmacSha256 (U.fromString "key") (U.fromString "some test message")
  mapM_ print [showDigest a, showDigest b]