packages feed

crypton-2.3.1 / Crypto / Cipher / ChaChaPoly1305.hs

{-# LANGUAGE GeneralizedNewtypeDeriving #-}-- |-- Module      : Crypto.Cipher.ChaChaPoly1305-- License     : BSD-style-- Maintainer  : Vincent Hanquez <vincent@snarc.org>-- Stability   : stable-- Portability : good---- A simple AEAD scheme using ChaCha20 and Poly1305. See-- <https://tools.ietf.org/html/rfc8439 RFC 8439>.---- The State is not modified in place, so each function changing the State,-- returns a new State.---- Authenticated Data need to be added before any call to 'encrypt' or 'decrypt',-- and once all the data has been added, then 'finalizeAAD' need to be called.---- Once 'finalizeAAD' has been called, no further 'appendAAD' call should be make.---- >import Data.ByteString.Char8 as B-- >import Data.ByteArray-- >import Crypto.Error-- >import Crypto.Cipher.ChaChaPoly1305 as C-- >-- >encrypt-- >    :: ByteString -- nonce (12 random bytes)-- >    -> ByteString -- symmetric key-- >    -> ByteString -- optional associated data (won't be encrypted)-- >    -> ByteString -- input plaintext to be encrypted-- >    -> CryptoFailable ByteString -- ciphertext with a 128-bit tag attached-- >encrypt nonce key header plaintext = do-- >    st1 <- C.initialize <$> C.key key <*> C.nonce12 nonce-- >    let-- >        st2 = C.finalizeAAD $ C.appendAAD header st1-- >        (out, st3) = C.encrypt plaintext st2-- >        auth = C.finalize st3-- >    return $ out `B.append` Data.ByteArray.convert authmodule Crypto.Cipher.ChaChaPoly1305 (    -- * AEAD    ChaCha20Poly1305,    aeadChacha20poly1305Init,    -- * Low level    State,    Key,    key,    Nonce,    XNonce,    nonce12,    nonce8,    nonce24,    incrementNonce,    initialize,    initializeX,    appendAAD,    finalizeAAD,    encrypt,    decrypt,    finalize,) whereimport Control.Monad (when)import qualified Crypto.Cipher.ChaCha as ChaChaimport Crypto.Cipher.Typesimport Crypto.Errorimport Crypto.Internal.ByteArray (    ByteArray,    ByteArrayAccess,    Bytes,    ScrubbedBytes, )import qualified Crypto.Internal.ByteArray as Bimport Crypto.Internal.Importsimport qualified Crypto.Internal.Poly1305 as PolyKeyimport qualified Crypto.MAC.Poly1305 as Poly1305import qualified Data.ByteArray.Pack as Pimport Data.Memory.Endianimport Foreign.Ptrimport Foreign.Storable-- | A ChaChaPoly1305 State.---- The state is immutable, and only new state can be createddata State    = State        !ChaCha.State        !Poly1305.State        !Word64 -- AAD length        !Word64 -- ciphertext length        !Word64 -- most ciphertext the block counter allows-- | A ChaChaPoly1305 State.type ChaCha20Poly1305 = State-- | Valid Nonce for ChaChaPoly1305.---- It can be created with 'nonce8' or 'nonce12'data Nonce = Nonce8 Bytes | Nonce12 Bytesinstance ByteArrayAccess Nonce where    length (Nonce8 n) = B.length n    length (Nonce12 n) = B.length n    withByteArray (Nonce8 n) = B.withByteArray n    withByteArray (Nonce12 n) = B.withByteArray n-- | Extended nonce for XChaChaPoly1305.newtype XNonce = Nonce24 Bytesinstance ByteArrayAccess XNonce where    length (Nonce24 n) = B.length n    withByteArray (Nonce24 n) = B.withByteArray n-- Based on the following pseudo code:---- chacha20_aead_encrypt(aad, key, iv, constant, plaintext):--     nonce = constant | iv--     otk = poly1305_key_gen(key, nonce)--     ciphertext = chacha20_encrypt(key, 1, nonce, plaintext)--     mac_data = aad | pad16(aad)--     mac_data |= ciphertext | pad16(ciphertext)--     mac_data |= num_to_4_le_bytes(aad.length)--     mac_data |= num_to_4_le_bytes(ciphertext.length)--     tag = poly1305_mac(mac_data, otk)--     return (ciphertext, tag)pad16 :: Word64 -> Bytespad16 n    | modLen == 0 = B.empty    | otherwise = B.replicate (16 - modLen) 0  where    modLen = fromIntegral (n `mod` 16)-- | Nonce smart constructor 12 bytes IV, nonce constructornonce12 :: ByteArrayAccess iv => iv -> CryptoFailable Noncenonce12 iv    | B.length iv /= 12 = CryptoFailed CryptoError_IvSizeInvalid    | otherwise = CryptoPassed . Nonce12 . B.convert $ iv-- | 8 bytes IV, nonce constructornonce8    :: ByteArrayAccess ba    => ba    -- ^ 4 bytes constant    -> ba    -- ^ 8 bytes IV    -> CryptoFailable Noncenonce8 constant iv    | B.length constant /= 4 = CryptoFailed CryptoError_IvSizeInvalid    | B.length iv /= 8 = CryptoFailed CryptoError_IvSizeInvalid    | otherwise = CryptoPassed . Nonce8 . B.concat $ [constant, iv]-- | 24 bytes IV, extended nonce constructornonce24    :: ByteArrayAccess ba    => ba -> CryptoFailable XNoncenonce24 iv    | B.length iv /= 24 = CryptoFailed CryptoError_IvSizeInvalid    | otherwise = CryptoPassed . Nonce24 . B.convert $ iv-- | Increment a nonceincrementNonce :: Nonce -> NonceincrementNonce (Nonce8 n) = Nonce8 $ incrementNonce' n 4incrementNonce (Nonce12 n) = Nonce12 $ incrementNonce' n 0incrementNonce' :: Bytes -> Int -> BytesincrementNonce' b offset = B.copyAndFreeze b $ \s ->    loop (s `plusPtr` offset) (B.length b - offset)  where    -- the carry stops at the last byte; all 0xff wraps to all zero    loop :: Ptr Word8 -> Int -> IO ()    loop _ 0 = return ()    loop p n = do        r <- (+) 1 <$> peek p        poke p r        when (r == 0) $ loop (p `plusPtr` 1) (n - 1)-- | A ChaCha20Poly1305 key: thirty-two bytes, checked once here rather than-- at every use, so that 'initialize' and 'initializeX' cannot fail.newtype Key = Key ScrubbedBytes    deriving (ByteArrayAccess, Eq, NFData)-- | Take thirty-two bytes for a key.  A different length is reported as-- 'CryptoError_KeySizeInvalid'; nothing else about a key can be wrong.key :: ByteArrayAccess ba => ba -> CryptoFailable Keykey k    | B.length k /= 32 = CryptoFailed CryptoError_KeySizeInvalid    | otherwise = CryptoPassed $ Key $ B.convert k-- | Initialize a new ChaChaPoly1305 State from a 'key' and a nonce made-- with 'nonce8' or 'nonce12'.---- With a 96-bit nonce the block counter is 32 bits, as in RFC 8439, so one-- message is at most 2^38 - 64 bytes; going past that is an error.initialize :: Key -> Nonce -> Stateinitialize k (Nonce8 nonce) = initialize' maxBound k nonce-- RFC 8439: with a 96-bit nonce the counter is 32 bits and block 0 is the-- Poly1305 key, so a message is at most 2^38 - 64 bytesinitialize k (Nonce12 nonce) = initialize' (2 ^ (38 :: Int) - 64) k nonceinitialize' :: Word64 -> Key -> Bytes -> Stateinitialize' limit k nonce = initFromRootState limit (ChaCha.initialize 20 k nonce)initFromRootState :: Word64 -> ChaCha.State -> StateinitFromRootState limit rootState = State encState polyState 0 0 limit  where    (polyKey, encState) = ChaCha.generate rootState 64    -- 64 bytes are generated so the ChaCha state advances a whole block, and    -- the first 32 of them are the key, so there is no length left to check    polyState = Poly1305.initialize (PolyKey.Key (B.take 32 polyKey))-- | Initialize a new XChaChaPoly1305 State---- The key length needs to be 256 bits, and the nonce-- procured using `nonce24`.initializeX :: Key -> XNonce -> StateinitializeX k (Nonce24 nonce) = initFromRootState maxBound (ChaCha.initializeX 20 k nonce)-- | Append Authenticated Data to the State and return-- the new modified State.---- Once no further call to this function need to be make,-- the user should call 'finalizeAAD'appendAAD :: ByteArrayAccess ba => ba -> State -> StateappendAAD ba (State encState macState aadLength plainLength limit) =    State encState newMacState newLength plainLength limit  where    newMacState = Poly1305.update macState ba    newLength = aadLength + fromIntegral (B.length ba)-- | Finalize the Authenticated Data and return the finalized StatefinalizeAAD :: State -> StatefinalizeAAD (State encState macState aadLength plainLength limit) =    State encState newMacState aadLength plainLength limit  where    newMacState = Poly1305.update macState $ pad16 aadLength-- | Encrypt a piece of data and returns the encrypted Data and the-- updated State.encrypt :: ByteArray ba => ba -> State -> (ba, State)encrypt input (State encState macState aadLength plainLength limit)    | tooLong plainLength limit input = error tooLongMessage    | otherwise =        (output, State newEncState newMacState aadLength newPlainLength limit)  where    (output, newEncState) = ChaCha.combine encState input    newMacState = Poly1305.update macState output    newPlainLength = plainLength + fromIntegral (B.length input)-- | Decrypt a piece of data and returns the decrypted Data and the-- updated State.decrypt :: ByteArray ba => ba -> State -> (ba, State)decrypt input (State encState macState aadLength plainLength limit)    | tooLong plainLength limit input = error tooLongMessage    | otherwise =        (output, State newEncState newMacState aadLength newPlainLength limit)  where    (output, newEncState) = ChaCha.combine encState input    newMacState = Poly1305.update macState input    newPlainLength = plainLength + fromIntegral (B.length input)-- Past the limit the 32-bit counter would carry into the nonce, and the-- keystream would be that of the next nonce.tooLong :: ByteArrayAccess ba => Word64 -> Word64 -> ba -> BooltooLong used limit input = fromIntegral (B.length input) > limit - usedtooLongMessage :: StringtooLongMessage = "ChaChaPoly1305: message longer than the nonce's counter allows"-- | Generate an authentication tag from the State.finalize :: State -> Poly1305.Authfinalize (State _ macState aadLength plainLength _) =    Poly1305.finalize $        Poly1305.updates            macState            [ pad16 plainLength            , either (error "finalize: internal error") id $                P.fill 16 (P.putStorable (toLE aadLength) >> P.putStorable (toLE plainLength))            ]-- | Setting up AEAD for ChaCha20Poly1305.aeadChacha20poly1305Init    :: (ByteArrayAccess k, ByteArrayAccess n)    => k -> n -> CryptoFailable (AEAD ChaCha20Poly1305)aeadChacha20poly1305Init k nonce = do    st0 <- initialize <$> key k <*> nonce12 nonce    return $ AEAD model (AEADState False st0)  where    model =        AEADModeImpl            { aeadImplAppendHeader = \(AEADState done st) aad ->                -- after the message, as before: the header is padded at once                if done                    then AEADState True (finalizeAAD $ appendAAD aad st)                    else AEADState False (appendAAD aad st)            , aeadImplEncrypt = \st plain ->                AEADState True <$> encrypt plain (headerDone st)            , aeadImplDecrypt = \st cipher ->                AEADState True <$> decrypt cipher (headerDone st)            , aeadImplFinalize = \st _ ->                let Poly1305.Auth tag = finalize (headerDone st) in AuthTag tag            }-- | The state behind the t'AEAD' interface, which may append the header in-- several pieces: RFC 8439 pads the header as a whole, so the padding waits-- for the message or the tag.  'True' once it has been added.data AEADState = AEADState !Bool !StateheaderDone :: AEADState -> StateheaderDone (AEADState True st) = stheaderDone (AEADState False st) = finalizeAAD st