我试图将一个随机字符串(恰好是一个数字)“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 编译器,我认为有两种类型的 Bytestring。
完整代码为:
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]’
最佳答案
问题是 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]
关于haskell - 尝试将随机字符串传递给 Haskell 中的 SHA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55693172/