2.5. Symmetric Encryption

Symmetric encryption functions are implemented using the AES cryptosystem.

2.5.1. Functions

crypto.SymmetricEncrypt(key: bytes, iv: bytes, plaintext: bytes) bytes

Encrypts plaintext using AES-CBC mode with the provided key and initialization vector iv, and returns the resulting ciphertext. Raises an error if either key or iv is not 128 bits (16 bytes) in length.

The input plaintext does not need to be a multiple of the block cipher size; this function will automatically add padding prior to encryption (via the PKCS#7 padding method).

Parameters:
  • key (bytes) – The symmetric key to use to encrypt

  • iv (bytes) – The initialization vector

  • plaintext (bytes) – The plaintext to encrypt

Returns:

The resulting ciphertext as a byte string

Return type:

bytes

Raises:

ValueError – if key or iv is not 128 bits long (16 bytes)

Note

As a reminder, in CBC mode, the ciphertext includes the initialization vector, so you do not need to store iv separately.

Warning

Every time something is encrypted with key, a new iv should be generated. Avoid reusing an iv with a given key; in particular, do not use a constant iv value.

crypto.SymmetricDecrypt(key: bytes, ciphertext: bytes) bytes

Decrypts ciphertext using the provided key. Raises an error if key is not 128 bits (16 bytes) in length.

If the underlying plaintext message was padded in crypto.SymmetricEncrypt (i.e. because it was not a multiple of the block cipher size), this function will automatically strip the padding after decryption, so you don’t have to worry about padding after decrypting a message. However, this function will not raise an error if the padding was invalid, so you need to make sure that you’ve verified the integrity of the ciphertext before decrypting.

Parameters:
  • key (bytes) – The symmetric key to use to decrypt

  • ciphertext (bytes) – The ciphertext to decrypt

Returns:

The resulting plaintext as a byte string

Return type:

bytes

Raises:

ValueError – if key is not 128 bits long (16 bytes)