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 providedkey
and initialization vectoriv
, and returns the resulting ciphertext. Raises an error if eitherkey
oriv
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
oriv
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 newiv
should be generated. Avoid reusing aniv
with a givenkey
; in particular, do not use a constantiv
value.
- crypto.SymmetricDecrypt(key: bytes, ciphertext: bytes) bytes
Decrypts
ciphertext
using the providedkey
. Raises an error ifkey
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)