Skip to content

Instantly share code, notes, and snippets.

@palevell
Created December 17, 2019 11:00
Show Gist options
  • Save palevell/bb034b559bb9dde9911c97219b6889ad to your computer and use it in GitHub Desktop.
Save palevell/bb034b559bb9dde9911c97219b6889ad to your computer and use it in GitHub Desktop.
This is the best example of Fernet encryption that I have found.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# crypto03.py - Monday, December 16, 2019
# Ref: https://www.thepythoncode.com/article/encrypt-decrypt-files-symmetric-python
""" This is the best example of Fernet encryption that I have found """
__version__ = '1.0.0'
from datetime import datetime
from shutil import copy2
from cryptography.fernet import Fernet
from tzlocal import get_localzone
def main():
# generate and write a new key
# write_key()
# load the previously generated key
key = load_key()
message = "some secret message".encode()
print("Message to be encrypted: %s" % message)
# initialize the Fernet class
f = Fernet(key)
# encrypt the message
encrypted = f.encrypt(message)
# print how it looks
print(encrypted)
decrypted_encrypted = f.decrypt(encrypted)
print(decrypted_encrypted)
# uncomment this if it's the first time you run the code, to generate the key
# write_key()
# load the key
key = load_key()
# file name
file = "data.csv"
# encrypt it
encrypt(file, key)
# copy it
copy2(file, file + '.encrypted')
# decrypt the file
decrypt(file, key)
return
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)
def load_key():
"""
Loads the key from the current directory named `key.key`
"""
return open("key.key", "rb").read()
def encrypt(filename, key):
"""
Given a filename (str) and key (bytes), it encrypts the file and write it
"""
f = Fernet(key)
with open(filename, "rb") as file:
# read all file data
file_data = file.read()
# encrypt data
encrypted_data = f.encrypt(file_data)
# write the encrypted file
with open(filename, "wb") as file:
file.write(encrypted_data)
return
def decrypt(filename, key):
"""
Given a filename (str) and key (bytes), it decrypts the file and write it
"""
f = Fernet(key)
with open(filename, "rb") as file:
# read the encrypted data
encrypted_data = file.read()
# decrypt data
decrypted_data = f.decrypt(encrypted_data)
# write the original file
with open(filename, "wb") as file:
file.write(decrypted_data)
return
def init():
print("Run Start: %s" % _run_dt)
return
def eoj():
print("Run Stop : %s" % datetime.now(tz).replace(microsecond=0))
return
def debug_breakpoint():
pass
return
if __name__ == '__main__':
_run_utc = datetime.now()
tz = get_localzone()
_run_dt = _run_utc.astimezone(tz).replace(microsecond=0)
_fdate = _run_dt.strftime("%Y-%m-%d")
init()
main()
eoj()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment