ecc_aes.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from Crypto.Cipher import AES
  2. from Crypto.Hash import SHA256
  3. from Crypto.PublicKey import ECC
  4. from Crypto.Util.Padding import pad, unpad
  5. class ECC_AES:
  6. def __init__(self, curve='P-256'):
  7. self.curve = curve
  8. self._aes_key = None
  9. self._private_key = None
  10. def _derive_aes_key(self, ecc_key, nonce):
  11. if not self._aes_key:
  12. hasher = SHA256.new()
  13. hasher.update(ecc_key.export_key(format='DER') + nonce.encode())
  14. self._aes_key = hasher.digest()[:32]
  15. return self._aes_key
  16. def generate_key_pair(self):
  17. private_key = ECC.generate(curve=self.curve)
  18. public_key = private_key.public_key()
  19. pem_private = private_key.export_key(format='PEM')
  20. pem_public = public_key.export_key(format='PEM')
  21. return pem_private, pem_public
  22. def load_private_key(self, private_key_pem):
  23. self._private_key = ECC.import_key(private_key_pem)
  24. self._aes_key = None
  25. def encrypt(self, text, nonce):
  26. if not self._private_key:
  27. raise ValueError("Private key not loaded")
  28. # Generate AES key using ECC private key and nonce
  29. aes_key = self._derive_aes_key(self._private_key, nonce)
  30. # Encrypt data using AES key
  31. cipher = AES.new(aes_key, AES.MODE_ECB)
  32. padded_text = pad(text.encode(), AES.block_size)
  33. ciphertext = cipher.encrypt(padded_text)
  34. return ciphertext
  35. def decrypt(self, ciphertext, nonce):
  36. if not self._private_key:
  37. raise ValueError("Private key not loaded")
  38. # Generate AES key using ECC private key and nonce
  39. aes_key = self._derive_aes_key(self._private_key, nonce)
  40. # Decrypt data using AES key
  41. cipher = AES.new(aes_key, AES.MODE_ECB)
  42. padded_plaintext = cipher.decrypt(ciphertext)
  43. plaintext = unpad(padded_plaintext, AES.block_size)
  44. return plaintext.decode()
  45. if __name__ == '__main__':
  46. ecc_aes = ECC_AES()
  47. # Generate key pairs for the user
  48. private_key, public_key = ecc_aes.generate_key_pair()
  49. ecc_aes.load_private_key(private_key)
  50. nonce = "THIS-IS-USER-ID"
  51. print(private_key)
  52. # Encrypt a message
  53. message = "Hello, this is a secret message!"
  54. encrypted_message = ecc_aes.encrypt(message, nonce)
  55. print(f"Encrypted message: {encrypted_message.hex()}")
  56. # Decrypt the message
  57. decrypted_message = ecc_aes.decrypt(encrypted_message, nonce)
  58. print(f"Decrypted message: {decrypted_message}")
  59. # Check if the original message and decrypted message are the same
  60. assert message == decrypted_message, "Original message and decrypted message do not match"