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

Crypto.Encrypt.Secretbox

Description

Symmetric authenticated encryption.

It is best to import this module qualified:

import qualified Crypto.Encrypt.Secretbox as Secretbox

encrypted = Secretbox.create key nonce message
decrypted = Secretbox.open key nonce encrypted

A secretbox is an abstraction from NaCl. 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 first, store it somewhere (it is just a sequence of bytes), and when you need it in the future, you open it 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

create 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 = Secretbox.create key nonce message
  • key is the secret key used for encryption. See Crypto.Key for how to get one.
  • nonce is an extra noise that ensures that is required for security. See Crypto.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, open will refuse to decrypt it.

open #

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 = Secretbox.open key nonce encrypted
  • key and nonce are the same that were used for encryption.
  • encrypted is the output of create.

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