Encrypting a message in Python (AES)
To encrypt and decrypt a message in Python, you can use libraries like cryptography that offer robust and easy-to-use encryption methods. Below is a complete example of how to encrypt and decrypt a message using the cryptography library with the AES (Advanced Encryption Standard) algorithm.
First, ensure you have the cryptography library installed. If not, you can install it using:
pip install cryptography
Here’s a Python example for encrypting and decrypting a message using cryptography:
[crayon-6a617aed949ff128802738/]
Explanation of the Code:
- Generate a Key:
generate_key()creates a new encryption key using theFernet.generate_key()method. - Save the Key:
save_key()stores the key in a file for later use. - Load the Key:
load_key()reads the key from a file. - Encrypt a Message:
encrypt_message()takes a plaintext message and encrypts it using the provided key. - Decrypt a Message:
decrypt_message()decrypts the encrypted message using the corresponding key.
In the usage example, a new key is generated and saved to a file named secret.key. This key is then loaded to encrypt and decrypt a test message.