Symmetric Key Encryption: Fernet
Python has a robust cryptography library offering Fernet, a secure, best-practice encryption scheme. Fernet employs AES CBC encryption, HMAC signature, and version and timestamp information to protect data. Generating a key with Fernet.generate_key() is recommended.
from cryptography.fernet import Fernet
key = Fernet.generate_key()
message = 'John Doe'
token = Fernet(key).encrypt(message.encode())
decrypted_message = Fernet(key).decrypt(token).decode() # 'John Doe'
Alternatives:
Obscuring: If only obscurity is needed, base64 encoding can suffice. For URL safety, use urlsafe_b64encode().
import base64
obscured_message = base64.urlsafe_b64encode(b'Hello world!') # b'eNrzSM3...='
Integrity Only: HMAC can provide data integrity assurance without encryption.
import hmac
import hashlib
key = secrets.token_bytes(32)
signature = hmac.new(key, b'Data', hashlib.sha256).digest()
AES-GCM Encryption: AES-GCM provides both encryption and integrity, without padding.
import base64
key = secrets.token_bytes(32)
ciphertext = aes_gcm_encrypt(b'Data', key) # base64-encoded ciphertext and tag
decrypted_data = aes_gcm_decrypt(ciphertext, key) # b'Data'
Other Approaches:
AES CFB: Similar to CBC without padding.
import base64
key = secrets.token_bytes(32)
ciphertext = aes_cfb_encrypt(b'Data', key) # base64-encoded ciphertext and IV
decrypted_data = aes_cfb_decrypt(ciphertext, key) # b'Data'
AES ECB: Caution: Insecure! Not recommended for real-world applications.
import base64
key = secrets.token_bytes(32)
ciphertext = aes_ecb_encrypt(b'Data', key) # base64-encoded ciphertext
decrypted_data = aes_ecb_decrypt(ciphertext, key) # b'Data'
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3