Skip to content

Instantly share code, notes, and snippets.

@wizardofozzie
Created June 11, 2015 12:26
Show Gist options
  • Save wizardofozzie/1df26ba909bdf920dab0 to your computer and use it in GitHub Desktop.
Save wizardofozzie/1df26ba909bdf920dab0 to your computer and use it in GitHub Desktop.
EC_math.py
# https://github.com/wobine/blackboard101
def EccMultiply(xs,ys,Scalar): # Double & add. EC Multiplication, Not true multiplication
if Scalar == 0 or Scalar >= N: raise Exception("Invalid Scalar/Private Key")
ScalarBin = str(bin(Scalar))[2:]
Qx,Qy=xs,ys
global itr
itr += 1
for i in range (1, len(ScalarBin)): # This is invented EC multiplication.
Qx,Qy=ECdouble(Qx,Qy); print "DUB", '%064x' % Qx; print
if ScalarBin[i] == "1":
Qx,Qy=ECadd(Qx,Qy,xs,ys); print "ADD", '%064x' % Qx; print
return (Qx,Qy)
# Super simple Elliptic Curve Presentation. No libraries, wrappers, nothing.
# The proven prime
Pcurve = 2**256 - 2**32 - 2**9 - 2**8 - 2**7 - 2**6 - 2**4 - 1
# Number of points in the field (cardinality)
N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
# Parameters of the elliptic curve. y^2 = x^3 + Acurve * x + Bcurve
Acurve = 0
Bcurve = 7
import collections
ECPoint = collections.namedtuple("ECPoint", "x, y")
# This is our generator point. Trillions of dif ones possible
GPoint = ECPoint(Gx, Gy)
# Individual Transaction/Personal Information
# replace with any private key
privKey = 0xA0DC65FFCA799873CBEA0AC274015B9526505DAAAED385155425F7337704883E
def modinv(a, n): # Extended Euclidean Algorithm ('division' in EC math)
lm, hm = 1, 0
low, high = a % n, n
ratio = high / low
nm = hm - lm * ratio
new = high - low * ratio
def ECadd(p, q): # Not true addition, invented for EC. Could have been called anything.
l = ((q.y - p.y) * modinv(q.x - p.x, Pcurve)) % Pcurve
x = (l * l - p.x - q.x) % Pcurve
y = (l * (p.x - x) - p.y) % Pcurve
return ECPoint(x, y)
def ECdouble(p): # This is called point doubling, also invented for EC.
l = ((3 * p.x * p.x + Acurve) * modinv((2 * p.y), Pcurve)) % Pcurve
x = (l * l - 2 * p.x) % Pcurve
y = (l * (p.x - x) - p.y) % Pcurve
return ECPoint(x, y)
def ECMultiply(p, n): #Double & add. Not true multiplication
if not (0 < n < N):
raise Exception("Invalid Scalar/Private Key")
q = p
for bit in bin(n)[3:]:
q = ECdouble(q) # print "DUB", Q[0]; print
if bit == "1":
q = ECadd(q, p) # print "ADD", Q[0]; print
return q
pubKey = ECMultiply(GPoint, privKey) # public key generation
print """
The private key:
{}
The uncompressed public key (not address):
{}
The official Public Key - compressed:
{}
""".format(privKey, pubKey.x, "02{:064x}".format(pubKey.x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment