From 27e2d2d2bc6e4a3ca1d61ed9117421e2bbcefcf8 Mon Sep 17 00:00:00 2001 From: mratsim Date: Sun, 2 Dec 2018 19:28:42 +0100 Subject: [PATCH] Implement to Montgomery domain conversion --- README.md | 5 +++-- constantine/field_fp.nim | 4 ++-- constantine/montgomery.nim | 9 ++++++++- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index dc854b0..0460f82 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,9 @@ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) ![Stability: experimental](https://img.shields.io/badge/stability-experimental-orange.svg) -This library provides constant time finite field primitives. -The main use will be for implementation of elliptic curve cryptography +This library provides constant time finite field primitives for implementation of elliptic curve cryptography. + +Warning ⚠️: The library is in development state. ## Installation diff --git a/constantine/field_fp.nim b/constantine/field_fp.nim index a442654..a9a79ff 100644 --- a/constantine/field_fp.nim +++ b/constantine/field_fp.nim @@ -160,14 +160,14 @@ template scaleadd_impl(a: var Fp, c: Limb) = sub(a, Fp.P, tooBig) func scaleadd*(a: var Fp, c: Limb) = - ## Scale-accumulate + ## Scale-accumulate modulo P ## ## With a word W = 2^LimbBitSize and a field Fp ## Does a <- a * W + c (mod p) scaleadd_impl(a, c) func scaleadd*(a: var Fp, c: static Limb) = - ## Scale-accumulate + ## Scale-accumulate modulo P ## ## With a word W = 2^LimbBitSize and a field Fp ## Does a <- a * W + c (mod p) diff --git a/constantine/montgomery.nim b/constantine/montgomery.nim index 64a009e..934bc21 100644 --- a/constantine/montgomery.nim +++ b/constantine/montgomery.nim @@ -69,5 +69,12 @@ func montyMagic*(M: static BigInt): static Limb = for _ in static(0 ..< k): result *= 2 + M * result # x' = x(2 + ax) (`+` to avoid negating at the end) -# func toMonty*[P: static BigInt](a: Fp[P], montyMagic: Limb): Montgomery[P] = +func toMonty*[P: static BigInt](a: Fp[P]): Montgomery[P] = + ## Convert a big integer over Fp to it's montgomery representation + ## over Fp. + ## i.e. Does "a * (2^LimbSize)^W (mod p), where W is the number + ## of words needed to represent p in base 2^LimbSize + result = a + for i in static(countdown(P.limbs.high, 0)): + scaleadd(result, 0)