-- S2K.hs: OpenPGP (RFC4880) string-to-key conversion
-- Copyright © 2013  Clint Adams
-- This software is released under the terms of the Expat license.
-- (See the LICENSE file).

module Codec.Encryption.OpenPGP.S2K (
  string2Key
) where

import Codec.Encryption.OpenPGP.Types
import qualified Crypto.Hash.SHA1 as SHA1
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL

string2Key :: Integral a => S2K -> a -> BL.ByteString -> B.ByteString
string2Key (Simple SHA1) ksz bs
    | 20 < ksz = error "FIXME"
    | otherwise = B.take (fromIntegral ksz) . SHA1.hashlazy $ bs
string2Key (Salted SHA1 salt) ksz bs = string2Key (Simple SHA1) ksz (BL.append (BL.fromChunks [salt]) bs)
string2Key (IteratedSalted SHA1 salt cnt) ksz bs = string2Key (Simple SHA1) ksz (BL.take (fromIntegral cnt) . BL.cycle $ BL.append (BL.fromChunks [salt]) bs)
string2Key _ _ _ = error "FIXME"