2
0

create_keys.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import os
  2. import rsa
  3. from cryptography.hazmat.backends import default_backend
  4. #from cryptography.hazmat.primitives.asymmetric import rsa
  5. from cryptography.hazmat.primitives import serialization
  6. from cryptography.fernet import Fernet
  7. def make_keys(contract_name):
  8. # create pubkey and private key for new contract
  9. (public_key,private_key)=rsa.newkeys(2048)
  10. # save them in contract folder
  11. path = f'contract_keys\\{contract_name}\\'
  12. os.makedirs(path, exist_ok=True)
  13. # write pubkey
  14. with open(path + 'publickey.key','wb') as f:
  15. f.write(public_key.save_pkcs1('PEM'))
  16. # write private key
  17. with open(path + 'privatekey.key','wb') as f:
  18. f.write(private_key.save_pkcs1('PEM'))
  19. # create semmetric key
  20. symmetric_key = Fernet.generate_key()
  21. with open(path + 'symmetric.key','wb') as f:
  22. f.write(symmetric_key)
  23. # retrieve public key
  24. def get_keys(contract_name):
  25. path = 'contract_keys\\' + contract_name + '\\publickey.key'
  26. # retreive public key form path
  27. with open(path, 'rb') as f:
  28. return rsa.PublicKey.load_pkcs1(f.read())
  29. # retrieve symmetric key
  30. def get_symmetric_key(contract_name):
  31. path = 'contract_keys\\' + contract_name + '\\symmetric.key'
  32. # read semmetric key from file
  33. with open(path, 'rb') as f:
  34. return f.read()
  35. # get private key
  36. def get_private_key(contract_name):
  37. path = 'contract_keys\\' + contract_name + '\\privatekey.key'
  38. # read private key from file
  39. with open(path, 'rb') as f:
  40. return rsa.PrivateKey.load_pkcs1(f.read())
  41. # get key in plain text (only public key)
  42. def get_plain_key(contract_name):
  43. path = 'contract_keys\\' + contract_name + '\\publickey.key'
  44. # read file and remove unnecessary suf
  45. with open(path, 'rt') as f:
  46. return f.read().split('-----')[2].strip().replace('\n', '')