我已经用Haskell编写了PBKDF2算法的新版本。它通过了RFC 6070中列出的几乎所有HMAC-SHA-1测试向量,但效率不高。我该如何改进代码?
当我在测试向量上运行它时,第三个案例(请参见下文)永远不会完成(我在2010年的Macbook Pro上运行了半个多小时)。
我认为问题出在“foldl'”上。使用“foldr”会更好吗?还是我需要使用可变数组?
当我在测试向量上运行它时,第三个案例(请参见下文)永远不会完成(我在2010年的Macbook Pro上运行了半个多小时)。
我认为问题出在“foldl'”上。使用“foldr”会更好吗?还是我需要使用可变数组?
{-# LANGUAGE BangPatterns #-}
{- Copyright 2013, G. Ralph Kuntz, MD. All rights reserved. LGPL License. -}
module Crypto where
import Codec.Utils (Octet)
import qualified Data.Binary as B (encode)
import Data.Bits (xor)
import qualified Data.ByteString.Lazy.Char8 as C (pack)
import qualified Data.ByteString.Lazy as L (unpack)
import Data.List (foldl')
import Data.HMAC (hmac_sha1)
import Text.Bytedump (dumpRaw)
-- Calculate the PBKDF2 as a hexadecimal string
pbkdf2
:: ([Octet] -> [Octet] -> [Octet]) -- pseudo random function (HMAC)
-> Int -- hash length in bytes
-> String -- password
-> String -- salt
-> Int -- iterations
-> Int -- derived key length in bytes
-> String
pbkdf2 prf hashLength password salt iterations keyLength =
let
passwordOctets = stringToOctets password
saltOctets = stringToOctets salt
totalBlocks =
ceiling $ (fromIntegral keyLength :: Double) / fromIntegral hashLength
blockIterator message acc =
foldl' (\(a, m) _ ->
let !m' = prf passwordOctets m
in (zipWith xor a m', m')) (acc, message) [1..iterations]
in
dumpRaw $ take keyLength $ foldl' (\acc block ->
acc ++ fst (blockIterator (saltOctets ++ intToOctets block)
(replicate hashLength 0))) [] [1..totalBlocks]
where
intToOctets :: Int -> [Octet]
intToOctets i =
let a = L.unpack . B.encode $ i
in drop (length a - 4) a
stringToOctets :: String -> [Octet]
stringToOctets = L.unpack . C.pack
-- Calculate the PBKDF2 as a hexadecimal string using HMAC and SHA-1
pbkdf2HmacSha1
:: String -- password
-> String -- salt
-> Int -- iterations
-> Int -- derived key length in bytes
-> String
pbkdf2HmacSha1 =
pbkdf2 hmac_sha1 20
第三个测试向量
Input:
P = "password" (8 octets)
S = "salt" (4 octets)
c = 16777216
dkLen = 20
Output:
DK = ee fe 3d 61 cd 4d a4 e4
e9 94 5b 3d 6b a2 15 8c
26 34 e9 84 (20 octets)
foldl'
参数中的m
。由于m
是一个列表,您需要使用例如deepSeq
来强制执行所有内容。 - opqdonutByteString
上运行(可以将其视为Word8
向量),而不是Octet
列表。虽然这不是减慢速度的唯一原因,但这也是一个有些棘手的算法,因为您可以调整它以花费任何您想要的时间,所以测试起来有些困难。 - J. Abrahamson