rsa.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. # -*- coding:utf-8 -*-
  2. import hashlib
  3. from Crypto.Cipher import PKCS1_OAEP, AES
  4. from Crypto.PublicKey import RSA
  5. from Crypto.Random import get_random_bytes
  6. from core.helper.lru_cache import LRUCache
  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 = PKCS1_OAEP.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. tenant_rsa_keys = LRUCache(capacity=1000)
  30. def get_decrypt_decoding(tenant_id):
  31. rsa_key = tenant_rsa_keys.get(tenant_id)
  32. if rsa_key:
  33. cipher_rsa = PKCS1_OAEP.new(rsa_key)
  34. return rsa_key, cipher_rsa
  35. filepath = "privkeys/{tenant_id}".format(tenant_id=tenant_id) + "/private.pem"
  36. cache_key = 'tenant_privkey:{hash}'.format(hash=hashlib.sha3_256(filepath.encode()).hexdigest())
  37. private_key = redis_client.get(cache_key)
  38. if not private_key:
  39. try:
  40. private_key = storage.load(filepath)
  41. except FileNotFoundError:
  42. raise PrivkeyNotFoundError("Private key not found, tenant_id: {tenant_id}".format(tenant_id=tenant_id))
  43. redis_client.setex(cache_key, 120, private_key)
  44. rsa_key = RSA.import_key(private_key)
  45. cipher_rsa = PKCS1_OAEP.new(rsa_key)
  46. tenant_rsa_keys.put(tenant_id, rsa_key)
  47. return rsa_key, cipher_rsa
  48. def decrypt_token_with_decoding(encrypted_text, rsa_key, cipher_rsa):
  49. if encrypted_text.startswith(prefix_hybrid):
  50. encrypted_text = encrypted_text[len(prefix_hybrid):]
  51. enc_aes_key = encrypted_text[:rsa_key.size_in_bytes()]
  52. nonce = encrypted_text[rsa_key.size_in_bytes():rsa_key.size_in_bytes() + 16]
  53. tag = encrypted_text[rsa_key.size_in_bytes() + 16:rsa_key.size_in_bytes() + 32]
  54. ciphertext = encrypted_text[rsa_key.size_in_bytes() + 32:]
  55. aes_key = cipher_rsa.decrypt(enc_aes_key)
  56. cipher_aes = AES.new(aes_key, AES.MODE_EAX, nonce=nonce)
  57. decrypted_text = cipher_aes.decrypt_and_verify(ciphertext, tag)
  58. else:
  59. decrypted_text = cipher_rsa.decrypt(encrypted_text)
  60. return decrypted_text.decode()
  61. def decrypt(encrypted_text, tenant_id):
  62. rsa_key, cipher_rsa = get_decrypt_decoding(tenant_id)
  63. return decrypt_token_with_decoding(encrypted_text, rsa_key, cipher_rsa)
  64. class PrivkeyNotFoundError(Exception):
  65. pass