Skip to content

Instantly share code, notes, and snippets.

@skywalker365
Forked from byt3bl33d3r/ecdh_eke.py
Created September 28, 2022 15:14
Show Gist options
  • Save skywalker365/9e79aae2c01b7fb323d20ee5f2a10540 to your computer and use it in GitHub Desktop.
Save skywalker365/9e79aae2c01b7fb323d20ee5f2a10540 to your computer and use it in GitHub Desktop.

Revisions

  1. @byt3bl33d3r byt3bl33d3r created this gist Oct 13, 2018.
    59 changes: 59 additions & 0 deletions ecdh_eke.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import hashes, padding
    from cryptography.hazmat.primitives.asymmetric import ec
    from cryptography.hazmat.primitives.kdf.hkdf import HKDF
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    from secrets import token_bytes


    class DiffieHellman:
    def __init__(self):
    self.diffieHellman = ec.generate_private_key(ec.SECP384R1(), default_backend())
    self.public_key = self.diffieHellman.public_key()
    self.IV = token_bytes(16)

    def encrypt(self, public_key, secret):
    shared_key = self.diffieHellman.exchange(ec.ECDH(), public_key)
    derived_key = HKDF(
    algorithm=hashes.SHA256(),
    length=32,
    salt=None,
    info=None,
    backend=default_backend()
    ).derive(shared_key)

    aes = Cipher(algorithms.AES(derived_key), modes.CBC(self.IV), backend=default_backend())
    encryptor = aes.encryptor()

    padder = padding.PKCS7(128).padder()
    padded_data = padder.update(secret.encode()) + padder.finalize()
    return encryptor.update(padded_data) + encryptor.finalize()

    def decrypt(self, public_key, secret, iv):
    shared_key = self.diffieHellman.exchange(ec.ECDH(), public_key)
    derived_key = HKDF(
    algorithm=hashes.SHA256(),
    length=32,
    salt=None,
    info=None,
    backend=default_backend()
    ).derive(shared_key)

    aes = Cipher(algorithms.AES(derived_key), modes.CBC(iv), backend=default_backend())
    decryptor = aes.decryptor()
    decrypted_data = decryptor.update(secret) + decryptor.finalize()

    unpadder = padding.PKCS7(128).unpadder()
    return unpadder.update(decrypted_data) + unpadder.finalize()


    text = "Hello World!"

    alice = DiffieHellman()
    bob = DiffieHellman()

    encrypted_message = bob.encrypt(alice.public_key, text)
    print(encrypted_message)

    decrypted_message = alice.decrypt(bob.public_key, encrypted_message, bob.IV)
    print(decrypted_message)