-
-
Save icostan/6fc21c23ef965911c50abda6a46f2b64 to your computer and use it in GitHub Desktop.
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
def ec_multiply(m, px, py, pn) | |
nx, ny = px, py | |
qx, qy = 0, 0 | |
while m > 0 | |
qx, qy = ec_add qx, qy, nx, ny, pn if m&1 == 1 | |
nx, ny = ec_double nx, ny, pn | |
m >>= 1 | |
end | |
[qx, qy] | |
end | |
def ec_add(ax, ay, bx, by, pn) | |
return [ax, ay] if bx == 0 && by == 0 | |
return [bx, by] if ax == 0 && ay == 0 | |
return ec_double(ax, ay, pn) if ax == bx && ay == by | |
i_bax = inverse(ax - bx, pn) | |
slope = ((ay - by) * i_bax) % pn | |
x = (slope**2 - ax - bx) % pn | |
y = (slope*(ax - x) - ay) % pn | |
[x, y] | |
end | |
def ec_double(px, py, pn) | |
i_2y = inverse(2 * py, pn) | |
slope = (3 * px**2 * i_2y) % pn | |
x = (slope**2 - 2 * px) % pn | |
y = (slope*(px - x) - py) % pn | |
[x, y] | |
end | |
def inverse(n, p) | |
gcd, x, y = extended_euclidean_algorithm(n, p) | |
(n * x + p * y) % p == gcd || raise('invalid gcd') | |
gcd == 1 || raise('no multiplicative inverse') | |
x % p | |
end | |
def extended_euclidean_algorithm(a, b) | |
s, old_s = 0, 1 | |
t, old_t = 1, 0 | |
r, old_r = b, a | |
while r != 0 | |
quotient = old_r / r | |
old_r, r = r, old_r - quotient * r | |
old_s, s = s, old_s - quotient * s | |
old_t, t = t, old_t - quotient * t | |
end | |
[old_r, old_s, old_t] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment