Skip to content

Instantly share code, notes, and snippets.

@volonbolon
Created April 12, 2018 18:59
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save volonbolon/ab707ecf2ccc97be19a71282ffeff461 to your computer and use it in GitHub Desktop.
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