Created
October 11, 2020 06:14
-
-
Save acdimalev/a31eae999d96ac8a81666f940a27f76a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 findme_packet_format import * | |
>>> | |
>>> # generate a public / private key pair for demonstration | |
>>> # curve and backend are hard-coded for convenience | |
>>> private = ec.generate_private_key(curve, backend) | |
>>> public = private.public_key() | |
>>> | |
>>> # take a peek at what the serialized public key looks like | |
>>> encode_public_key(public).hex() | |
'bbae416a73aac8b64786006b4b358d7261cc57eb780aeb61c15537d88eb9a6e68d48a0f737aafde8c99f6821be199aef49da91f7e60f3a42d524be06aac811a5' | |
>>> | |
>>> # test that serializing + deserializing the public key works | |
>>> reference = public.public_numbers() | |
>>> example = decode_public_key(encode_public_key(public)).public_numbers() | |
>>> reference == example | |
True |
This file contains hidden or 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
import cryptography.hazmat.backends | |
from cryptography.hazmat.backends import default_backend | |
from cryptography.hazmat.primitives import hashes | |
from cryptography.hazmat.primitives.asymmetric import ec | |
from cryptography.hazmat.primitives.serialization import (Encoding, PublicFormat) | |
# instantiate a common backend and curve | |
backend = default_backend() | |
curve = ec.SECP256K1() | |
def encode_public_key(public_key): | |
"""Encode public key to 64 bytes. | |
Serialization format for network packets and hash entries. | |
""" | |
public_numbers = public_key.public_numbers() | |
(x, y) = (public_numbers.x, public_numbers.y) | |
return x.to_bytes(32, 'big') + y.to_bytes(32, 'big') | |
def decode_public_key(encoded_public_key): | |
"""Decode public key from 64 bytes.""" | |
x = int.from_bytes(encoded_public_key[:32], 'big') | |
y = int.from_bytes(encoded_public_key[32:], 'big') | |
return backend.load_elliptic_curve_public_numbers( | |
ec.EllipticCurvePublicNumbers(x, y, curve), | |
) | |
# TODO: signatures |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment