pj_crypto_v2/utils/symmetric_keys_manager_1.py
2019-11-12 15:24:37 +01:00

91 lines
3.1 KiB
Python

# Symmetric crypto lib
from cryptography.fernet import Fernet
#UniqueID
import uuid
# To get user home directory
from pathlib import Path
# Home made RSA Keys lib
from utils.rsa_tenamortech_utils import *
def gen_rand_session_id():
return str(uuid.uuid4())
def gen_sym_key_and_save(public_key_client):
key = Fernet.generate_key()
root_file_path = '.auth_server_test/'
path = root_file_path + 'server'
path_clients_pub_keys = root_file_path + 'server/clients_pub_keys'
session_id = gen_rand_session_id()
file = open('.clients_keys', 'ab') # changed from 'wb' to 'w+' ...
file.write((session_id + " ").encode('utf-8'))
file.write(key + (" ").encode('utf-8')) # The key is type bytes still
file.write(('0\n').encode('utf-8'))
file.close()
# --- Store the client public Key for next time.
# --- Public keys are stored in '.auth_server_test/server/clients_pub_keys/session_id.pub'
keys_dir_path = Path.home() / path_clients_pub_keys
# Path exists ? If not we will create it
keys_dir_path.mkdir(exist_ok=True)
public_key_client_pem = public_key_serializer(public_key_client)
key_path = keys_dir_path / (str(session_id) + '.pub')
with open(str(key_path), 'wb') as f:
f.write(public_key_client_pem)
return key
def reload_session_sym_key(sessionid):
root_file_path = '.auth_server_test/'
path = root_file_path + 'server/'
path_clients_pub_keys = path + 'clients_pub_keys/'
filename='.clients_keys'
session_id_found = False
# --- Open session file
with open(filename) as f:
line = f.readline().rstrip()
while(line and session_id_found == False):
# each line contains (session_id, sym_key, sym_key_nb_use)
# Those infos are spaced with "space" char, so we use 'split' fuction to get an array
cur_client_infos = line.split()
# If we find the given sessionID:
if(cur_client_infos[0] == sessionid): # cur_client_info[0] is the session_id stored in the cur line
session_id_found = True
line = f.readline().rstrip()
# --- We found the given sessionID, so we will now load the corresponding client public key we previously stored.
if session_id_found == True:
with open(str(path_clients_pub_keys + cur_client_infos[0] + '.pub'), "rb") as key_file:
public_key_client = serialization.load_pem_public_key(
key_file.read(),
backend=default_backend()
)
# --- Return the Symmetric Key used with this client and the PEM formated client public Key
return (cur_client_infos[1],public_key_client_pem)
else:
# Return Error tuple
return (-1,'')
def encrypt_msg_symmetric(msg, key):
msg = msg.encode()
f_key = Fernet(key)
enc_msg = f_key.encrypt(msg)
#print(encrypted)
#decrypted = f.decrypt(encrypted)
#print(decrypted)
#gen_sym_key_and_save()
#print(reload_session_sym_key("26c9f89a-f8e1-4b22-83bd-417c5047e527"))