crypto-sodium-0.0.5.0: Easy-and-safe-to-use high-level cryptography based on Sodium
Safe HaskellNone
LanguageHaskell2010

Crypto.Sodium.Encrypt.Symmetric

Description

Symmetric authenticated encryption.

It is best to import this module qualified:

import qualified Crypto.Sodium.Encrypt.Symmetric as Symmetric

encrypted = Symmetric.encrypt key nonce message
decrypted = Symmetric.decrypt key nonce encrypted

In NaCl this is know as a “Secretbox”. One way to think about it is to imagine that you are putting data into a box protected by a secret key. You “create” such a box using encrypt, store it somewhere (it is just a sequence of bytes), and when you need it in the future, you “open” it with decrypt using the same secret key.

Synopsis

Keys

type Key a = SizedByteArray CRYPTO_SECRETBOX_KEYBYTES a #

Encryption key that can be used for Secretbox.

This type is parametrised by the actual data type that contains bytes. This can be, for example, a ByteString, but, since this is a secret key, it is better to use ScrubbedBytes.

toKey :: ByteArrayAccess ba => ba -> Maybe (Key ba) #

Make a Key from an arbitrary byte array.

This function returns Just if and only if the byte array has the right length to be used as a key with a Secretbox.

Nonce

type Nonce a = SizedByteArray CRYPTO_SECRETBOX_NONCEBYTES a #

Nonce that can be used for Secretbox.

This type is parametrised by the actual data type that contains bytes. This can be, for example, a ByteString.

toNonce :: ByteArrayAccess ba => ba -> Maybe (Nonce ba) #

Make a Nonce from an arbitrary byte array.

This function returns Just if and only if the byte array has the right length to be used as a nonce with a Secretbox.

Encryption/decryption

encrypt Source #

Arguments

:: (ByteArrayAccess keyBytes, ByteArrayAccess nonceBytes, ByteArrayAccess ptBytes, ByteArray ctBytes) 
=> Key keyBytes

Secret key

-> Nonce nonceBytes

Nonce

-> ptBytes

Plaintext message

-> ctBytes 

Encrypt a message.

encrypted = Symmetric.encrypt key nonce message
  • key is the secret key used for encryption. See Crypto.Sodium.Key for how to get one.
  • nonce is an extra noise that is required for security. See Crypto.Sodium.Nonce for how to work with it.
  • message is the data you are encrypting.

This function adds authentication data, so if anyone modifies the cyphertext, decrypt will refuse to decrypt it.

decrypt Source #

Arguments

:: (ByteArrayAccess keyBytes, ByteArrayAccess nonceBytes, ByteArray ptBytes, ByteArrayAccess ctBytes) 
=> Key keyBytes

Secret key

-> Nonce nonceBytes

Nonce

-> ctBytes

Encrypted message (cyphertext)

-> Maybe ptBytes 

Decrypt a message.

decrypted = Symmetric.decrypt key nonce encrypted
  • key and nonce are the same that were used for encryption.
  • encrypted is the output of encrypt.

This function will return Nothing if the encrypted message was tampered with after it was encrypted.