整数到IV类型转换

时间:2018-03-15 10:24:28

标签: haskell encryption cryptography

我使用this库中的AES256和this库中的类型。这里ctrCombine函数在IV类型中采用IV cipher(初始化向量)。

我想从我已经拥有的一些整数中生成它,而不是从IV函数生成随机makeIV

  1. 是否可以将任何整数转换为'IV密码'类型?

  2. 如果有可能,我该怎么办?

1 个答案:

答案 0 :(得分:1)

makeIV并不会像您暗示的那样生成随机IV。这正是你想要的功能。只需将整数序列化为足够长度的字节串,然后在该bytestring上调用makeIV:

makeIV $ runPut (putWord64be (fromIntegral i) >>putWord64be (fromIntegral (i `shiftR` 64)))

其中put操作来自cereal包。您可以使用binary代替cereal,但是您必须确保获得严格的字节字符串。

编辑:一个更完整的例子:

import Data.Binary.Put
import Crypto.Cipher.Types
import Crypto.Cipher.AES (AES256)
import Data.ByteArray (unpack)
import qualified Data.ByteString.Lazy as LBS
import Data.Bits (shiftR)

example :: Integer -> IV AES256
example i =
  maybe (error "foo") id $
  -- ^^ makeIV returns a `Maybe` (Nothing for IVs of incorrect size
  makeIV $ LBS.toStrict $
  --      ^^ makeIV requires strict bytestrings
     runPut (putWord64be (fromIntegral i) >>
             putWord64be (fromIntegral (i `shiftR` 64)))
  -- ^^ Construct your IV bytestring however you'd like

main = do print $ unpack (example 0)
          print $ unpack (example 1)
          print $ unpack (example (2^63))
          print $ unpack (example (2^65))
          print $ unpack (example (2^112))
          print $ unpack (example (2^120))

请注意,这并不使用加密密码类型,因为它与cryptonite平行并且与密码分离。您应该使用来自cryptonite的IV类型(参见Cryptonite' Crypto.Cipher.Types模块)。

相关问题