Python Simple Encrypt Decrypt String
Chapter:
Python
Last Updated:
24-09-2023 03:02:00 UTC
Program:
/* ............... START ............... */
from cryptography.fernet import Fernet
# Generate a random key for encryption
def generate_key():
return Fernet.generate_key()
# Encrypt a string using a key
def encrypt_message(key, message):
cipher_suite = Fernet(key)
encrypted_message = cipher_suite.encrypt(message.encode())
return encrypted_message
# Decrypt a string using a key
def decrypt_message(key, encrypted_message):
cipher_suite = Fernet(key)
decrypted_message = cipher_suite.decrypt(encrypted_message)
return decrypted_message.decode()
# Example usage
if __name__ == "__main__":
# Generate a key (keep it secret and safe)
secret_key = generate_key()
# Message to be encrypted
message_to_encrypt = "Hello, World!"
# Encrypt the message
encrypted_message = encrypt_message(secret_key, message_to_encrypt)
print("Encrypted Message:", encrypted_message)
# Decrypt the message
decrypted_message = decrypt_message(secret_key, encrypted_message)
print("Decrypted Message:", decrypted_message)
/* ............... END ............... */
Notes:
-
Encrypting and decrypting a string in Python can be done using various encryption algorithms and libraries. One simple way to achieve this is by using the cryptography library, which provides a high-level interface for various cryptographic operations. Here's an example of how to encrypt and decrypt a string using the Fernet symmetric encryption scheme from the cryptography library:
- First, you need to install the cryptography library if you haven't already. You can install it using pip: pip install cryptography
- In this example, we generate a random key, use it to encrypt a message, and then use the same key to decrypt the message. Make sure to keep your encryption key secure, as it's necessary to decrypt the message.