繁体   English   中英

试图将随机字符串传递给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,并且我转换为错误的一种,如何正确转换随机字符串?

如果我将导入合格的Data.ByteString.Char8替换为C,则对@Cubic的回答更进一步。

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]’

问题是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]

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

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

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

import Data.ByteString.Lazy.Char8 as C

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM