Skip to content

Instantly share code, notes, and snippets.

@nakov
Created March 7, 2018 13:08
Show Gist options
  • Save nakov/50e0f9e62d91fd8f7c188de75a22b42e to your computer and use it in GitHub Desktop.
Save nakov/50e0f9e62d91fd8f7c188de75a22b42e to your computer and use it in GitHub Desktop.
Compress / decompress elliptic curve public key in Pyhton
from pycoin.ecdsa import CurveFp, Point
from nummaster.basic import sqrtmod
def compress_key_pair(key_pair):
return (key_pair.x(), key_pair.y() % 2)
def uncompress_key(curve, compressed_key):
x, is_odd = compressed_key
p, a, b = curve.p(), curve.a(), curve.b()
y = sqrtmod(pow(x, 3, p) + a * x + b, p)
if bool(is_odd) == bool(y & 1):
return (x, y)
return (x, p - y)
curve = CurveFp(17, 0, 7)
p = Point(curve, 2, 10)
print(f"original key = {p}")
compressed_p = compress_key_pair(p)
print(f"compressed = {compressed_p}")
restored_p = uncompress_key(curve, compressed_p)
print(f"uncompressed = {restored_p}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment