Python3 Encrytion / Decryption Example using Cryptography Package
Encryption / Decryption Code
from cryptography.fernet import Fernet
def generate_key():
"""
Generate a new encryption key.
"""
return Fernet.generate_key()
def encrypt_password(password, key):
"""
Encrypt the given password using the provided key.
Parameters:
password (str): The password to be encrypted.
key (bytes): The encryption key.
Returns:
bytes: The encrypted password.
"""
cipher_suite = Fernet(key)
encrypted_password = cipher_suite.encrypt(password.encode())
return encrypted_password
def decrypt_password(encrypted_password, key):
"""
Decrypt the given encrypted password using the provided key.
Parameters:
encrypted_password (bytes): The encrypted password.
key (bytes): The encryption key.
Returns:
str: The decrypted password.
"""
cipher_suite = Fernet(key)
decrypted_password = cipher_suite.decrypt(encrypted_password).decode()
return decrypted_password
def main():
"""
Main function to run the password encryption and decryption process.
"""
# Generate the encryption key
key = generate_key()
# Get the plain text password from the user
plain_text_password = input("Enter the password to encrypt: ")
# Encrypt the password
encrypted_password = encrypt_password(plain_text_password, key)
print("Key: ", key)
print("Encrypted password:", encrypted_password)
# Decrypt the password
decrypted_password = decrypt_password(encrypted_password, key)
print("Decrypted password:", decrypted_password)
if __name__ == "__main__":
main()
Example Output
Enter the password to encrypt: Pa$$w0rd123!
Key: b'G5YLK1KdKpQZjT5p30Chd9SJ2KVc9e_7qeQ1EDufPHU='
Encrypted password: b'gAAAAABkw6rzPNKDivFJgvBMkY_07i2MI0ZOmXMw-oJgTPXzLS8p7SmJ6O7uDiL652s8AjHc5kEoL6KX3Wy-gp4cSgfdsted3g=='
Decrypted password: Pa$$w0rd123!
Process finished with exit code 0
0 Comments Received
Leave A Reply