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

时间:2019-04-15 16:04:46

标签: haskell random sha bytestring

我正在尝试将一个随机字符串(恰好是一个数字)“ 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]

看到字节串显然有两种类型,并且我转换为错误的字节串,如何正确转换随机字符串?

如果我替换了@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]’

3 个答案:

答案 0 :(得分:2)

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

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]

答案 1 :(得分:0)

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

通常,您几乎不需要Data.ByteString.Char8

答案 2 :(得分:0)

只需使用惰性字节串作为@leftaroundabout提到。您的尝试无效,因为您想从字符串中打包,因此您需要导入.Char8模块以实现该目标:

import Data.ByteString.Lazy.Char8 as C