create_keys.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. from cryptography.fernet import Fernet
  15. def make_keys(contract_name):
  16. #(pubkey,privkey)=rsa.newkeys(2048)
  17. private_key = rsa.generate_private_key(
  18. public_exponent=65537,
  19. key_size=2048,
  20. backend=default_backend()
  21. )
  22. public_key = private_key.public_key()
  23. pem = public_key.public_bytes(
  24. encoding=serialization.Encoding.PEM,
  25. format=serialization.PublicFormat.SubjectPublicKeyInfo
  26. )
  27. path = 'contract_keys\\' + contract_name + '\\'
  28. os.mkdir(path)
  29. with open(path + 'publickey.key','wb') as f:
  30. f.write(pem)
  31. pem = private_key.private_bytes(
  32. encoding=serialization.Encoding.PEM,
  33. format=serialization.PrivateFormat.PKCS8,
  34. encryption_algorithm=serialization.NoEncryption()
  35. )
  36. with open(path + 'privatekey.key','wb') as f:
  37. f.write(pem)
  38. symmetric_key = Fernet.generate_key()
  39. with open(path + 'symmetric.key','wb') as f:
  40. f.write(symmetric_key)
  41. def get_keys(contract_name):
  42. path = 'contract_keys\\' + contract_name + '\\publickey.key'
  43. with open(path, 'rb') as f:
  44. public_key = serialization.load_pem_public_key(
  45. f.read(),
  46. backend=default_backend()
  47. )
  48. return public_key
  49. def get_symmetric_key(contract_name):
  50. path = 'contract_keys\\' + contract_name + '\\symmetric.key'
  51. with open(path, 'rb') as f:
  52. return f.read()
  53. def get_private_key(contract_name):
  54. path = 'contract_keys\\' + contract_name + '\\privatekey.key'
  55. with open(path, "rb") as key_file:
  56. private_key = serialization.load_pem_private_key(
  57. key_file.read(),
  58. password=None,
  59. backend=default_backend()
  60. )
  61. return private_key
  62. def get_plain_key(contract_name):
  63. path = 'contract_keys\\' + contract_name + '\\publickey.key'
  64. with open(path, 'rt') as f:
  65. return f.read().split('-----')[2].strip().replace('\n', '')