rsa.py 2.5 KB

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