2
0

create_keys.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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(company):
  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. with open('companies\\' + company + '_publickey.key','wb') as f:
  27. f.write(pem)
  28. pem = private_key.private_bytes(
  29. encoding=serialization.Encoding.PEM,
  30. format=serialization.PrivateFormat.PKCS8,
  31. encryption_algorithm=serialization.NoEncryption()
  32. )
  33. with open('companies\\' + company + '_privatekey.key','wb') as f:
  34. f.write(pem)
  35. def get_keys(company):
  36. path = 'companies\\' + company + '_publickey.key'
  37. if not os.path.exists(path):
  38. make_keys(company)
  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