from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend # Key and initialization vector key = b'this_is_a_random_key' iv = b'this_is_a_random_iv_' # Cipher object cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()) # Encryption function def encrypt(cipher, plaintext): encryptor = cipher.encryptor() ciphertext = encryptor.update(plaintext) + encryptor.finalize() return ciphertext # Usage plaintext = b'secret message' ciphertext = encrypt(cipher, plaintext) print(ciphertext.hex())
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend # Key and initialization vector key = b'this_is_a_random_key' iv = b'this_is_a_random_iv_' # Cipher object cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()) # Decryption function def decrypt(cipher, ciphertext): decryptor = cipher.decryptor() plaintext = decryptor.update(ciphertext) + decryptor.finalize() return plaintext # Usage ciphertext = b'2ff2ba042002cd92e9451a522635c802' plaintext = decrypt(cipher, bytes.fromhex(ciphertext)) print(plaintext)This example decrypts the `ciphertext` using the same `key`, `iv`, and `backend` used in the previous example. We first create a `Cipher` object using the `key`, `iv`, and `backend`. We then define a `decrypt` function which takes in the `cipher` object and `ciphertext`, and returns the decrypted `plaintext`. Finally, we use the `decrypt` function to decrypt the `ciphertext` (which we convert from its hexadecimal representation to bytes using `bytes.fromhex()`) and print the resulting `plaintext`. In these examples, we used the `algorithms` and `modes` modules from the `cryptography.hazmat.primitives.ciphers` package to specify the algorithms and modes of operation to be used. We also used the `default_backend()` function from the `cryptography.hazmat.backends` module to specify the backend cryptography library to use (which is the default backend in this case).