From 8a0bacfc6d939f14108712dc5d37848dbc5121db Mon Sep 17 00:00:00 2001 From: Vincent Hanquez Date: Wed, 29 Jul 2015 09:49:49 +0100 Subject: [PATCH] [Poly1305] make initialize explicitely failable --- Crypto/Cipher/ChaChaPoly1305.hs | 2 +- Crypto/MAC/Poly1305.hs | 7 ++++--- tests/Poly1305.hs | 3 ++- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Crypto/Cipher/ChaChaPoly1305.hs b/Crypto/Cipher/ChaChaPoly1305.hs index bcd4dc7..a2db972 100644 --- a/Crypto/Cipher/ChaChaPoly1305.hs +++ b/Crypto/Cipher/ChaChaPoly1305.hs @@ -82,7 +82,7 @@ initialize key (Nonce nonce) where rootState = ChaCha.initialize 20 key nonce (polyKey, encState) = ChaCha.generate rootState 64 - polyState = Poly1305.initialize (B.take 32 polyKey :: ScrubbedBytes) + polyState = throwCryptoError $ Poly1305.initialize (B.take 32 polyKey :: ScrubbedBytes) appendAAD :: ByteArrayAccess ba => ba -> State -> State appendAAD ba (State encState macState aadLength plainLength) = diff --git a/Crypto/MAC/Poly1305.hs b/Crypto/MAC/Poly1305.hs index 46cda05..c264a92 100644 --- a/Crypto/MAC/Poly1305.hs +++ b/Crypto/MAC/Poly1305.hs @@ -29,6 +29,7 @@ import Foreign.C.Types import Data.Word import Crypto.Internal.ByteArray (ByteArrayAccess, ScrubbedBytes, Bytes) import qualified Crypto.Internal.ByteArray as B +import Crypto.Error -- | Poly1305 State newtype State = State ScrubbedBytes @@ -56,10 +57,10 @@ foreign import ccall unsafe "cryptonite_poly1305.h cryptonite_poly1305_finalize" -- | initialize a Poly1305 context initialize :: ByteArrayAccess key => key - -> State + -> CryptoFailable State initialize key - | B.length key /= 32 = error "Poly1305: key length expected 32 bytes" - | otherwise = State $ B.allocAndFreeze 84 $ \ctxPtr -> + | B.length key /= 32 = CryptoFailed $ CryptoError_MacKeyInvalid + | otherwise = CryptoPassed $ State $ B.allocAndFreeze 84 $ \ctxPtr -> B.withByteArray key $ \keyPtr -> c_poly1305_init (castPtr ctxPtr) keyPtr {-# NOINLINE initialize #-} diff --git a/tests/Poly1305.hs b/tests/Poly1305.hs index 505f9eb..1413d5e 100644 --- a/tests/Poly1305.hs +++ b/tests/Poly1305.hs @@ -5,6 +5,7 @@ import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B () import Imports +import Crypto.Error import qualified Crypto.MAC.Poly1305 as Poly1305 import qualified Data.ByteArray as B (convert) @@ -27,7 +28,7 @@ tests = testGroup "Poly1305" , testProperty "Chunking" $ \(Chunking chunkLen totalLen) -> let key = B.replicate 32 0 msg = B.pack $ take totalLen $ concat (replicate 10 [1..255]) - in Poly1305.auth key msg == Poly1305.finalize (foldr (flip Poly1305.update) (Poly1305.initialize key) (chunks chunkLen msg)) + in Poly1305.auth key msg == Poly1305.finalize (foldr (flip Poly1305.update) (throwCryptoError $ Poly1305.initialize key) (chunks chunkLen msg)) ] where chunks i bs