Created
May 22, 2017 20:58
-
-
Save nachivpn/9da6a1093295edcea53f138230820f52 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module PBKDF2 ( | |
pbkdf2, pbkdf2HmacSha1 | |
) where | |
import Data.HMAC (hmac_sha1) | |
import Text.Bytedump (dumpRaw) | |
import Control.DeepSeq | |
import OctetString | |
pbkdf2 :: (OctetString -> OctetString -> OctetString) -- pseudo random function (HMAC) | |
-> Int -- hash length in bytes | |
-> String -- password | |
-> String -- salt | |
-> Int -- iterations | |
-> Int -- derived key length in bytes | |
-> String -- derived key | |
pbkdf2 prf hlen pass salt c dkLen = | |
let p = strToOctet pass | |
s = strToOctet salt | |
l = ceiling $ (fromIntegral dkLen :: Double) / fromIntegral hlen | |
r = dkLen - (l - 1) * hlen | |
blocks' = map (blockFun p s c) [1..l] | |
in dumpRaw . take dkLen . concat $ blocks' | |
where | |
blockFun p s c i = | |
let plist = take c $ repeat p | |
in rHash plist (s ++ intToMSOctet i) | |
rHash :: [OctetString] -> OctetString -> OctetString | |
rHash [] _ = replicate hlen 0 | |
rHash (p:ps) s = let u_i = prf p s in u_i `xor'` rHash ps u_i | |
-- 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 -- derived key | |
pbkdf2HmacSha1 = pbkdf2 hmac_sha1 20 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment