| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- import hashlib
- import json
- import time
- import uuid
- import os
- from create_keys import make_keys
- from lib.contract import Contract
- from cryptography.fernet import Fernet
- import rsa
- 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:
- return rsa.PublicKey.load_pkcs1(f.read())
-
- # 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
- print(pubkey)
- # create the cipher
- cipher = Fernet(pubkey)
- # encrypt the data
- encrypted_data = cipher.encrypt(block_string)
- #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}')
|