Python cryptography can help us encrypt and decrypt string easily. In this tutorial, we will introduce how to do.
1.Install cryptography
pip install cryptography
2.Import library
from cryptography.fernet import Fernet
3.Create a key to encrypt string using Fernet.generate_key()
def write_key(): """ Generates a key and save it into a file """ key = Fernet.generate_key() with open("key.key", "wb") as key_file: key_file.write(key)
4.Read key to start to encrypt
def load_key(): """ Loads the key from the current directory named `key.key` """ return open("key.key", "rb").read()
5.Star to encrypt string
write_key() key = load_key() message = "some secret message".encode() f = Fernet(key) encrypted = f.encrypt(message)
encrypted is the encrypted string. Print it, it will be:
b'gAAAAABdjSdoqn4kx6XMw_fMx5YT2eaeBBCEue3N2FWHhlXjD6JXJyeELfPrKf0cqGaYkcY6Q0bS22ppTBsNTNw2fU5HVg-c-0o-KVqcYxqWAIG-LVVI_1U='
6.Decrypt string
decrypted_encrypted = f.decrypt(encrypted) print(decrypted_encrypted)
Run this code, you will see:
b'some secret message'