[chachapoly1305] properly handle the decryption, and change combine to encrypt.

This commit is contained in:
Vincent Hanquez 2015-07-29 07:24:46 +01:00
parent 169570c963
commit e064af5cba
2 changed files with 23 additions and 4 deletions

View File

@ -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

View File

@ -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)
]