import hashlib import json import time import uuid import os from create_keys import make_keys from lib.contract import Contract from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding class Transaction: def __init__(self): self.id = None self.data = None self.hash_value = None self.locked = False self.timestamp = 0 self.sender = None self.receiver = None def from_serialized(self, jsonobj: str): obj = json.loads(jsonobj) self.id = obj['id'] self.data = obj['data'] self.timestamp = obj['timestamp'] self.sender = obj['sender'] self.receiver = obj['receiver'] def set_serialized_contract(self, serialized): if not self.locked: self.id = str(uuid.uuid1()) self.data = serialized self.log('Serialized contract set') return True return False def set_contract(self, contract: Contract): if not self.locked: self.id = str(uuid.uuid1()) self.data = contract.serialize() self.log(f'Contract set: {contract.id} | {contract.title}') return True return False def serialize(self, out_json=False): obj = { 'id': self.id, 'timestamp': self.timestamp, 'data': self.data, 'sender': self.sender, 'receiver': self.receiver } self.log(f'Serialized') if out_json: return json.dumps(obj, sort_keys=True) return obj def lock_hash_finish(self): if not self.locked: self.timestamp = int(time.time()) self.locked = True self.hash() self.log('Locked') return True return False def get_keys(self, recipient): path = 'companies\\' + recipient + '_publickey.key' if not os.path.exists(path): make_keys(recipient) with open(path, 'rb') as f: public_key = serialization.load_pem_public_key( f.read(), backend=default_backend() return f # key_file = open(file, 'rb') # key_data = key_file.read() # key_file.close() # return key_data def hash(self, recipient=None): string_object = json.dumps(self.data, sort_keys=True) block_string = string_object.encode() # open the public key file pubkey = self.get_keys(recipient) #Sender public key - input field neccessary encrypted_data = pubkey.encrypt( block_string, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) #these lines only neccessary for key_encryption - solve the problem of bytes # open the symmetric key file for encryoting the file #skey = open('symmetric.key','rb') #key = skey.read() # encrypt the symmetric key file with the public key #encrypted_key = rsa.encrypt(key,pubkey) self.hash_value = encrypted_data self.log(f'Hashed: {self.hash_value}') return encrypted_data def log(self, text): print(f'[ TRANS ] {text}')