cryptonite-0.23: Cryptography Primitives sink

MaintainerVincent Hanquez <>
Safe HaskellNone



A simple AEAD scheme using ChaCha20 and Poly1305. See RFC 7539.

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

    :: 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.nonce12 nonce >>= C.initialize key
        st2 = C.finalizeAAD $ C.appendAAD header st1
        (out, st3) = C.encrypt plaintext st2
        auth = C.finalize st3
    return $ out `B.append` Data.ByteArray.convert auth



data State #

A ChaChaPoly1305 State.

The state is immutable, and only new state can be created

data Nonce #

Valid Nonce for ChaChaPoly1305.

It can be created with nonce8 or nonce12


ByteArrayAccess Nonce # 


length :: Nonce -> Int #

withByteArray :: Nonce -> (Ptr p -> IO a) -> IO a #

nonce12 :: ByteArrayAccess iv => iv -> CryptoFailable Nonce #

Nonce smart constructor 12 bytes IV, nonce constructor

nonce8 #


:: ByteArrayAccess ba 
=> ba

4 bytes constant

-> ba

8 bytes IV

-> CryptoFailable Nonce 

8 bytes IV, nonce constructor

incrementNonce :: Nonce -> Nonce #

Increment a nonce

initialize :: ByteArrayAccess key => key -> Nonce -> CryptoFailable State #

Initialize a new ChaChaPoly1305 State

The key length need to be 256 bits, and the nonce procured using either nonce8 or nonce12

appendAAD :: ByteArrayAccess ba => ba -> State -> State #

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

finalizeAAD :: State -> State #

Finalize the Authenticated Data and return the finalized State

encrypt :: ByteArray ba => ba -> State -> (ba, State) #

Encrypt a piece of data and returns the encrypted Data and the updated State.

decrypt :: ByteArray ba => ba -> State -> (ba, State) #

Decrypt a piece of data and returns the decrypted Data and the updated State.

finalize :: State -> Auth #

Generate an authentication tag from the State.