Last active
April 25, 2019 10:33
-
-
Save jaheba/a976048b0eea2dfdab67e1bf31c48e52 to your computer and use it in GitHub Desktop.
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
extern crate ramp; | |
use ramp::Int; | |
#[derive(PartialEq, Clone, Debug)] | |
struct Point { | |
x: Int, | |
y: Int, | |
} | |
fn point_add( | |
&Point { | |
x: ref p_x, | |
y: ref p_y, | |
}: &Point, | |
&Point { | |
x: ref q_x, | |
y: ref q_y, | |
}: &Point, | |
) -> Point { | |
let P = &Int::from_str_radix( | |
"115792089237316195423570985008687907853269984665640564039457584007908834671663", | |
10, | |
).unwrap(); | |
let P2 = &(P - Int::from(2)); | |
let lam = if p_x == q_x && p_y == q_y { | |
Int::from(3) * p_x.pow(2) * ((p_y + p_y) % P).pow_mod(P2, P) | |
} else { | |
(q_x - p_x).pow_mod(P2, P) * (q_y - p_y) % P | |
}; | |
let rx = (lam.pow(2) - p_x - q_x) % P; | |
let mut ry = (&lam * (p_x - &rx) - p_y) % P; | |
if ry < 0 { | |
ry = ry + P; | |
} | |
Point { x: rx, y: ry } | |
} | |
fn point_mul(p: &Point, mut d: u32) -> Point { | |
let mut n = p.clone(); | |
let mut q = None; | |
for _ in 0..256 { | |
let last_bit = d & 1 == 1; | |
d >>= 1; | |
if last_bit { | |
q = Some(q.map_or_else(|| n.clone(), |q| point_add(&q, &n))); | |
} | |
n = point_add(&n, &n); | |
} | |
q.unwrap() | |
} | |
fn main() { | |
let g = Point { | |
x: Int::from_str_radix( | |
"79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", | |
16, | |
).unwrap(), | |
y: Int::from_str_radix( | |
"483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", | |
16, | |
).unwrap(), | |
}; | |
let res = point_mul(&g, 125); | |
println!(" {}", res.x); | |
println!(" {}", res.y); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment