Python cryptography can help us encrypt and decrypt string easily. In this tutorial, we will introduce how to do.
pip install cryptography
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:
decrypted_encrypted = f.decrypt(encrypted) print(decrypted_encrypted)
Run this code, you will see:
b'some secret message'