rsa.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # -*- coding:utf-8 -*-
  2. import hashlib
  3. from Crypto.Cipher import AES
  4. from Crypto.PublicKey import RSA
  5. from Crypto.Random import get_random_bytes
  6. import libs.gmpy2_pkcs10aep_cipher as gmpy2_pkcs10aep_cipher
  7. from extensions.ext_redis import redis_client
  8. from extensions.ext_storage import storage
  9. def generate_key_pair(tenant_id):
  10. private_key = RSA.generate(2048)
  11. public_key = private_key.publickey()
  12. pem_private = private_key.export_key()
  13. pem_public = public_key.export_key()
  14. filepath = "privkeys/{tenant_id}".format(tenant_id=tenant_id) + "/private.pem"
  15. storage.save(filepath, pem_private)
  16. return pem_public.decode()
  17. prefix_hybrid = b"HYBRID:"
  18. def encrypt(text, public_key):
  19. if isinstance(public_key, str):
  20. public_key = public_key.encode()
  21. aes_key = get_random_bytes(16)
  22. cipher_aes = AES.new(aes_key, AES.MODE_EAX)
  23. ciphertext, tag = cipher_aes.encrypt_and_digest(text.encode())
  24. rsa_key = RSA.import_key(public_key)
  25. cipher_rsa = gmpy2_pkcs10aep_cipher.new(rsa_key)
  26. enc_aes_key = cipher_rsa.encrypt(aes_key)
  27. encrypted_data = enc_aes_key + cipher_aes.nonce + tag + ciphertext
  28. return prefix_hybrid + encrypted_data
  29. def get_decrypt_decoding(tenant_id):
  30. filepath = "privkeys/{tenant_id}".format(tenant_id=tenant_id) + "/private.pem"
  31. cache_key = 'tenant_privkey:{hash}'.format(hash=hashlib.sha3_256(filepath.encode()).hexdigest())
  32. private_key = redis_client.get(cache_key)
  33. if not private_key:
  34. try:
  35. private_key = storage.load(filepath)
  36. except FileNotFoundError:
  37. raise PrivkeyNotFoundError("Private key not found, tenant_id: {tenant_id}".format(tenant_id=tenant_id))
  38. redis_client.setex(cache_key, 120, private_key)
  39. rsa_key = RSA.import_key(private_key)
  40. cipher_rsa = gmpy2_pkcs10aep_cipher.new(rsa_key)
  41. return rsa_key, cipher_rsa
  42. def decrypt_token_with_decoding(encrypted_text, rsa_key, cipher_rsa):
  43. if encrypted_text.startswith(prefix_hybrid):
  44. encrypted_text = encrypted_text[len(prefix_hybrid):]
  45. enc_aes_key = encrypted_text[:rsa_key.size_in_bytes()]
  46. nonce = encrypted_text[rsa_key.size_in_bytes():rsa_key.size_in_bytes() + 16]
  47. tag = encrypted_text[rsa_key.size_in_bytes() + 16:rsa_key.size_in_bytes() + 32]
  48. ciphertext = encrypted_text[rsa_key.size_in_bytes() + 32:]
  49. aes_key = cipher_rsa.decrypt(enc_aes_key)
  50. cipher_aes = AES.new(aes_key, AES.MODE_EAX, nonce=nonce)
  51. decrypted_text = cipher_aes.decrypt_and_verify(ciphertext, tag)
  52. else:
  53. decrypted_text = cipher_rsa.decrypt(encrypted_text)
  54. return decrypted_text.decode()
  55. def decrypt(encrypted_text, tenant_id):
  56. rsa_key, cipher_rsa = get_decrypt_decoding(tenant_id)
  57. return decrypt_token_with_decoding(encrypted_text, rsa_key, cipher_rsa)
  58. class PrivkeyNotFoundError(Exception):
  59. pass