2
0

create_keys.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import rsa
  2. import os
  3. #from cryptography.fernet import Fernet
  4. # create the symmetric key only for the JSON file - we are going to only encrypt the keys
  5. #key = Fernet.generate_key()
  6. # write the symmetric key to a file
  7. #k = open('symmetric.key','wb')
  8. #k.write(key)
  9. #k.close()
  10. # create the pub & private keys for the parties
  11. from cryptography.hazmat.backends import default_backend
  12. from cryptography.hazmat.primitives.asymmetric import rsa
  13. from cryptography.hazmat.primitives import serialization
  14. def make_keys(contract_name):
  15. #(pubkey,privkey)=rsa.newkeys(2048)
  16. private_key = rsa.generate_private_key(
  17. public_exponent=65537,
  18. key_size=2048,
  19. backend=default_backend()
  20. )
  21. public_key = private_key.public_key()
  22. pem = public_key.public_bytes(
  23. encoding=serialization.Encoding.PEM,
  24. format=serialization.PublicFormat.SubjectPublicKeyInfo
  25. )
  26. path = 'contract_keys\\' + contract_name + '\\'
  27. os.mkdir(path)
  28. with open(path + 'publickey.key','wb') as f:
  29. f.write(pem)
  30. pem = private_key.private_bytes(
  31. encoding=serialization.Encoding.PEM,
  32. format=serialization.PrivateFormat.PKCS8,
  33. encryption_algorithm=serialization.NoEncryption()
  34. )
  35. with open(path + 'privatekey.key','wb') as f:
  36. f.write(pem)
  37. def get_keys(contract_name):
  38. path = 'contract_keys\\' + contract_name + '\\publickey.key'
  39. with open(path, 'rb') as f:
  40. public_key = serialization.load_pem_public_key(
  41. f.read(),
  42. backend=default_backend()
  43. )
  44. return public_key
  45. def get_private_key(contract_name):
  46. path = 'contract_keys\\' + contract_name + '\\privatekey.key'
  47. with open(path, "rb") as key_file:
  48. private_key = serialization.load_pem_private_key(
  49. key_file.read(),
  50. password=None,
  51. backend=default_backend()
  52. )
  53. return private_key
  54. def get_plain_key(contract_name):
  55. path = 'contract_keys\\' + contract_name + '\\publickey.key'
  56. with open(path, 'rt') as f:
  57. return f.read().split('-----')[2].strip().replace('\n', '')