Encryption is a tricky subject in any language. It is better to choose a library with active maintenance.
There are 2 best Python encryption libraries as follows.
cryptography includes both high-level recipes and low-level interfaces to common cryptographic algorithms such as symmetric ciphers, message digests, and key derivation functions.
Encrypt and decrypt text with cryptography’s high-level symmetric encryption recipe:
from cryptography.fernet import Fernet key = Fernet.generate_key() f = Fernet(key) encrypted_text = f.encrypt(b"This is a secret text message that needs to be hidden.") decrypted_text = f.decrypt(encrypted_text )
Encrypt and decrypt using AES
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes import os key = os.urandom(32) iv = os.urandom(16) cipher = Cipher(algorithms.AES(key), modes.CBC(iv)) encryptor = cipher.encryptor() ct = encryptor.update(b"This is a secret text") + encryptor.finalize() decryptor = cipher.decryptor() plain_text = decryptor.update(ct) + decryptor.finalize()
PyCryptodome is a self-contained Python package of low-level cryptographic primitives. It is a fork of PyCrypto, which brings a lot of enhancements with respect to the last official version of PyCrypto (2.6.1).
PyCryptodome supports Python 2.6 and 2.7, Python 3.4 and newer, and PyPy.
Encrypt data with AES:
from Crypto.Random import get_random_bytes key = get_random_bytes(16) cipher = AES.new(key, AES.MODE_EAX) ciphertext, tag = cipher.encrypt_and_digest(data) file_out = open("encrypted.bin", "wb") [ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ] file_out.close()
Generate RSA key:
from Crypto.PublicKey import RSA secret_code = "Unguessable" key = RSA.generate(2048) encrypted_key = key.export_key(passphrase=secret_code, pkcs=8, protection="scryptAndAES128-CBC") file_out = open("rsa_key.bin", "wb") file_out.write(encrypted_key) file_out.close() print(key.publickey().export_key())