Created
April 12, 2018 18:59
Star
You must be signed in to star a gist
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
import os | |
from random import SystemRandom | |
import ecdsa | |
p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F | |
order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 | |
# Remember the equiation we are using is `y^2 % p == x^3 + 7 | |
a = 0x0000000000000000000000000000000000000000000000000000000000000000 | |
b = 0x0000000000000000000000000000000000000000000000000000000000000007 | |
# This is the generator point defined in the standard | |
g = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8) | |
# First, let's define the curve | |
elliptic_curve_secp256k1 = ecdsa.ellipticcurve.CurveFp(p, a, b) | |
# And, from the curve, extract the generator | |
generator_secp256k1 = ecdsa.ellipticcurve.Point(elliptic_curve_secp256k1, g[0], g[1], order) | |
# Now, we need to define the object identifiers for the elliptic curve domain parameters | |
certicom_arc_oid = (1, 3, 132, 0, 10) | |
#Finally, the curve | |
secp256k1 = ecdsa.curves.Curve("SECP256k1", elliptic_curve_secp256k1, generator_secp256k1, certicom_arc_oid) | |
def private_key(): | |
# SystemRandom uses os.urandom to gather entropy. | |
# https://docs.python.org/2/library/random.html | |
# The random module also provides the SystemRandom class which uses the system function os.urandom() | |
# to generate random numbers from sources provided by the operating system. | |
key = sum([(SystemRandom().randrange(2) * 2 ** idx) for idx in range(256)]) | |
return key | |
def produce_public_compressed_key_from_point(point): | |
# Please, check https://iamvolonbolon.tumblr.com/post/172841967580/blockchain-public-key-representations | |
point_y_is_odd = point.y() & 1 | |
if point_y_is_odd: | |
key = '03' + '%064x' % point.x() | |
else: | |
key = '02' + '%064x' % point.x() | |
return key | |
if __name__ == "__main__": | |
secret_key = private_key() | |
print("Private Key: {}".format(hex(secret_key))) | |
public_key_point = secret_key * generator_secp256k1 | |
print("Public Key Point: ({}, {})".format(public_key_point.x(), public_key_point.x())) | |
public_key = '04' + '%064x' % public_key_point.x() + '%064x' % public_key_point.y() | |
print("Uncompressed Public Key: {}".format(public_key)) | |
pk = produce_public_compressed_key_from_point(public_key_point) | |
print("Compressed Public Key: {}".format(pk)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment