Created
March 7, 2018 13:08
-
-
Save nakov/50e0f9e62d91fd8f7c188de75a22b42e to your computer and use it in GitHub Desktop.
Compress / decompress elliptic curve public key in Pyhton
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 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