Created
May 6, 2023 07:42
-
-
Save callingmedic911/25c43f188fac518502e298ba13d32918 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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