From e064af5cba8c5e5aaf1edd7ac89aa2dd9407ce2b Mon Sep 17 00:00:00 2001 From: Vincent Hanquez Date: Wed, 29 Jul 2015 07:24:46 +0100 Subject: [PATCH] [chachapoly1305] properly handle the decryption, and change combine to encrypt. --- Crypto/Cipher/ChaChaPoly1305.hs | 15 ++++++++++++--- tests/ChaChaPoly1305.hs | 12 +++++++++++- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/Crypto/Cipher/ChaChaPoly1305.hs b/Crypto/Cipher/ChaChaPoly1305.hs index 4bf0bac..bcd4dc7 100644 --- a/Crypto/Cipher/ChaChaPoly1305.hs +++ b/Crypto/Cipher/ChaChaPoly1305.hs @@ -17,7 +17,8 @@ module Crypto.Cipher.ChaChaPoly1305 , initialize , appendAAD , finalizeAAD - , combine + , encrypt + , decrypt , finalize ) where @@ -96,14 +97,22 @@ finalizeAAD (State encState macState aadLength plainLength) = where newMacState = Poly1305.update macState $ pad16 aadLength -combine :: ByteArray ba => ba -> State -> (ba, State) -combine input (State encState macState aadLength plainLength) = +encrypt :: ByteArray ba => ba -> State -> (ba, State) +encrypt input (State encState macState aadLength plainLength) = (output, State newEncState newMacState aadLength newPlainLength) where (output, newEncState) = ChaCha.combine encState input newMacState = Poly1305.update macState output newPlainLength = plainLength + fromIntegral (B.length input) +decrypt :: ByteArray ba => ba -> State -> (ba, State) +decrypt input (State encState macState aadLength plainLength) = + (output, State newEncState newMacState aadLength newPlainLength) + where + (output, newEncState) = ChaCha.combine encState input + newMacState = Poly1305.update macState input + newPlainLength = plainLength + fromIntegral (B.length input) + finalize :: State -> Poly1305.Auth finalize (State _ macState aadLength plainLength) = Poly1305.finalize $ Poly1305.updates macState diff --git a/tests/ChaChaPoly1305.hs b/tests/ChaChaPoly1305.hs index 73fafe9..254fe28 100644 --- a/tests/ChaChaPoly1305.hs +++ b/tests/ChaChaPoly1305.hs @@ -20,12 +20,22 @@ tag = "\x1a\xe1\x0b\x59\x4f\x09\xe2\x6a\x7e\x90\x2e\xcb\xd0\x60\x06\x91" tests = testGroup "ChaChaPoly1305" [ testCase "V1" runEncrypt + , testCase "V1-decrypt" runDecrypt ] where runEncrypt = let ini = throwCryptoError $ AEAD.initialize key (throwCryptoError $ AEAD.nonce8 constant iv) afterAAD = AEAD.finalizeAAD (AEAD.appendAAD aad ini) - (out, afterEncrypt) = AEAD.combine plaintext afterAAD + (out, afterEncrypt) = AEAD.encrypt plaintext afterAAD outtag = AEAD.finalize afterEncrypt in propertyHoldCase [ eqTest "ciphertext" ciphertext out , eqTest "tag" tag (B.convert outtag) ] + + runDecrypt = + let ini = throwCryptoError $ AEAD.initialize key (throwCryptoError $ AEAD.nonce8 constant iv) + afterAAD = AEAD.finalizeAAD (AEAD.appendAAD aad ini) + (out, afterDecrypt) = AEAD.decrypt ciphertext afterAAD + outtag = AEAD.finalize afterDecrypt + in propertyHoldCase [ eqTest "plaintext" plaintext out + , eqTest "tag" tag (B.convert outtag) + ]