2021-11-25 23:12:20 +00:00
|
|
|
from os import environ, path
|
2021-11-23 13:00:03 +00:00
|
|
|
from cryptography.fernet import Fernet
|
|
|
|
|
|
|
|
def generate_keyfile():
|
2021-12-07 15:15:16 +00:00
|
|
|
with open('.security/.encryption.key', 'wb') as keyfile:
|
2021-11-23 13:00:03 +00:00
|
|
|
key = Fernet.generate_key()
|
|
|
|
keyfile.write(key)
|
|
|
|
|
|
|
|
def load_key():
|
2021-12-07 15:15:16 +00:00
|
|
|
with open('.security/.encryption.key', 'rb') as keyfile:
|
2021-11-23 13:00:03 +00:00
|
|
|
key = keyfile.read()
|
|
|
|
return key
|
|
|
|
|
|
|
|
def check_keyfile_exists():
|
2021-12-07 15:15:16 +00:00
|
|
|
return path.isfile('.security/.encryption.key')
|
2021-11-23 13:00:03 +00:00
|
|
|
|
2021-11-25 23:12:20 +00:00
|
|
|
def encrypt(input):
|
2021-11-23 13:00:03 +00:00
|
|
|
if not check_keyfile_exists():
|
|
|
|
generate_keyfile()
|
|
|
|
_encryption_key = load_key()
|
|
|
|
fernet = Fernet(_encryption_key)
|
2021-11-25 23:12:20 +00:00
|
|
|
if type(input) == str:
|
|
|
|
input = input.encode()
|
|
|
|
output = fernet.encrypt(input)
|
|
|
|
return output.decode()
|
|
|
|
if type(input) == dict:
|
|
|
|
output = {}
|
|
|
|
for key,value in input.items():
|
|
|
|
if type(value) == dict:
|
|
|
|
output[key] = encrypt(value)
|
|
|
|
else:
|
|
|
|
value = value.encode()
|
|
|
|
output[key] = fernet.encrypt(value)
|
|
|
|
output[key] = output[key].decode()
|
|
|
|
return output
|
2021-11-23 13:00:03 +00:00
|
|
|
|
|
|
|
def decrypt(input):
|
|
|
|
if not check_keyfile_exists():
|
|
|
|
raise EncryptionKeyMissing
|
|
|
|
_encryption_key = load_key()
|
|
|
|
fernet = Fernet(_encryption_key)
|
2021-11-30 18:06:24 +00:00
|
|
|
if type(input) == str:
|
|
|
|
input = input.encode()
|
|
|
|
output = fernet.decrypt(input)
|
|
|
|
return output.decode()
|
|
|
|
if type(input) == dict:
|
|
|
|
output = {}
|
|
|
|
for key, value in input.items():
|
|
|
|
if type(value) == dict:
|
|
|
|
output[key] = decrypt(value)
|
|
|
|
else:
|
|
|
|
value = value.encode()
|
|
|
|
output[key] = fernet.decrypt(value)
|
|
|
|
output[key] = output[key].decode()
|
|
|
|
return output
|
2021-11-23 13:00:03 +00:00
|
|
|
|
|
|
|
class EncryptionKeyMissing(Exception):
|
|
|
|
def __init__(self, message='There is no encryption keyfile.'):
|
|
|
|
self.message = message
|
|
|
|
super().__init__(self.message)
|