Skip to content

Instantly share code, notes, and snippets.

@callingmedic911
Created May 6, 2023 07:42
Show Gist options
  • Save callingmedic911/25c43f188fac518502e298ba13d32918 to your computer and use it in GitHub Desktop.
Save callingmedic911/25c43f188fac518502e298ba13d32918 to your computer and use it in GitHub Desktop.
from cryptography.hazmat.primitives.asymmetric import dh
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
# Generate our own private key and public key
parameters = dh.generate_parameters(generator=2, key_size=2048)
private_key = parameters.generate_private_key()
public_key = private_key.public_key()
# Serialize the public key and send it to the other party
serialized_public_key = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
# The other party receives the serialized public key and deserializes it
received_public_key = serialization.load_pem_public_key(
serialized_public_key,
backend=default_backend()
)
# Generate our shared secret
shared_secret = private_key.exchange(received_public_key)
# Generate a key from the shared secret using HKDF
derived_key = HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=None,
info=b'',
backend=default_backend()
).derive(shared_secret)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment