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.
<code class="python">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'</code>
Alternatives:
Obscuring: If only obscurity is needed, base64 encoding can suffice. For URL safety, use urlsafe_b64encode().
<code class="python">import base64 obscured_message = base64.urlsafe_b64encode(b'Hello world!') # b'eNrzSM3...='</code>
Integrity Only: HMAC can provide data integrity assurance without encryption.
<code class="python">import hmac import hashlib key = secrets.token_bytes(32) signature = hmac.new(key, b'Data', hashlib.sha256).digest()</code>
AES-GCM Encryption: AES-GCM provides both encryption and integrity, without padding.
<code class="python">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'</code>
Other Approaches:
AES CFB: Similar to CBC without padding.
<code class="python">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'</code>
AES ECB: Caution: Insecure! Not recommended for real-world applications.
<code class="python">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'</code>
The above is the detailed content of How to Enhance Data Protection with Advanced Encryption Techniques?. For more information, please follow other related articles on the PHP Chinese website!