aboutsummaryrefslogtreecommitdiff
path: root/src/Codec/Crypto/HKDF.hs
diff options
context:
space:
mode:
Diffstat (limited to 'src/Codec/Crypto/HKDF.hs')
-rw-r--r--src/Codec/Crypto/HKDF.hs33
1 files changed, 20 insertions, 13 deletions
diff --git a/src/Codec/Crypto/HKDF.hs b/src/Codec/Crypto/HKDF.hs
index bc1ea61..31d0be3 100644
--- a/src/Codec/Crypto/HKDF.hs
+++ b/src/Codec/Crypto/HKDF.hs
@@ -48,16 +48,23 @@ module Codec.Crypto.HKDF
-- to do so, specify the empty string as the associated data.
, AssociatedData(AssociatedData)
+ -- * Error handling
+ , Error
+
-- * Legacy functions
, md5
) where
+import Control.Monad ((>=>))
+import Control.Monad.Trans.Class (lift)
+import Control.Monad.Trans.Except (runExceptT)
import Foreign (allocaArray)
import Foreign.Marshal.Unsafe (unsafeLocalState)
import BTLS.BoringSSL.Digest (evpMaxMDSize)
import BTLS.BoringSSL.HKDF
-import BTLS.Buffer (onBufferOfMaxSize, packCUStringLen)
+import BTLS.Buffer (onBufferOfMaxSize', packCUStringLen)
+import BTLS.Result (Error, check)
import BTLS.Types
( Algorithm(Algorithm), AssociatedData(AssociatedData), Salt(Salt)
, SecretKey(SecretKey), noSalt
@@ -66,7 +73,7 @@ import Data.Digest (md5, sha1, sha224, sha256, sha384, sha512)
-- | Computes an HKDF. It is defined by
--
--- prop> hkdf md salt info len = expand md info len . extract md salt
+-- prop> hkdf md salt info len = extract md salt >=> expand md info len
--
-- but may be faster than calling the two functions individually.
hkdf ::
@@ -75,16 +82,16 @@ hkdf ::
-> AssociatedData
-> Int -- ^ The length of the derived key, in bytes.
-> SecretKey
- -> SecretKey
-hkdf md salt info outLen = expand md info outLen . extract md salt
+ -> Either [Error] SecretKey
+hkdf md salt info outLen = extract md salt >=> expand md info outLen
-- | Computes an HKDF pseudorandom key (PRK).
-extract :: Algorithm -> Salt -> SecretKey -> SecretKey
+extract :: Algorithm -> Salt -> SecretKey -> Either [Error] SecretKey
extract (Algorithm md) (Salt salt) (SecretKey secret) =
- SecretKey $
+ fmap SecretKey $
unsafeLocalState $
- onBufferOfMaxSize evpMaxMDSize $ \pOutKey pOutLen -> do
- hkdfExtract pOutKey pOutLen md secret salt
+ onBufferOfMaxSize' evpMaxMDSize $ \pOutKey pOutLen ->
+ check $ hkdfExtract pOutKey pOutLen md secret salt
-- | Computes HKDF output key material (OKM).
expand ::
@@ -92,10 +99,10 @@ expand ::
-> AssociatedData
-> Int -- ^ The length of the OKM, in bytes.
-> SecretKey
- -> SecretKey
+ -> Either [Error] SecretKey
expand (Algorithm md) (AssociatedData info) outLen (SecretKey secret) =
- SecretKey $
+ fmap SecretKey $
unsafeLocalState $
- allocaArray outLen $ \pOutKey -> do
- hkdfExpand pOutKey outLen md secret info
- packCUStringLen (pOutKey, outLen)
+ allocaArray outLen $ \pOutKey -> runExceptT $ do
+ check $ hkdfExpand pOutKey outLen md secret info
+ lift $ packCUStringLen (pOutKey, outLen)