From 26806655936224d4cd97ffe2745489bc7dc3a2c3 Mon Sep 17 00:00:00 2001 From: Hans Svensson Date: Mon, 17 Jan 2022 12:20:58 +0100 Subject: [PATCH] Improve pow by using crypto:mod_pow --- src/ecu_misc.erl | 13 ++++++++++++- src/ecu_secp256k1.erl | 11 ++--------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/ecu_misc.erl b/src/ecu_misc.erl index 41565e6..9f9dc3a 100644 --- a/src/ecu_misc.erl +++ b/src/ecu_misc.erl @@ -4,10 +4,21 @@ %%% Created : 13 Jan 2022 by Hans Svensson -module(ecu_misc). --export([eea/2, +-export([eea/2, exp_mod/3, hex_to_bin/1, bin_to_hex/1, pcomp/1]). +%% A^B mod P +exp_mod(_A, 0, _P) -> 1; +exp_mod(A, B, P) when A > 0 -> + binary:decode_unsigned(crypto:mod_pow(A, B, P)); +exp_mod(A, B, P) -> + X = exp_mod(-A, B, P), + case B rem 2 == 0 orelse X == 0 of + true -> X; + false -> P - X + end. + %% Extended Euclidean Algorithm eea(A, B) when ((A < 1) or (B < 1)) -> undefined; diff --git a/src/ecu_secp256k1.erl b/src/ecu_secp256k1.erl index 034f33e..28267bb 100644 --- a/src/ecu_secp256k1.erl +++ b/src/ecu_secp256k1.erl @@ -79,13 +79,7 @@ p_add({X1, Y1}, {X2, Y2}) -> Y3 = ?SUB(?MUL(M, ?SUB(X1, X3)), Y1), {X3, Y3}. -pow(_, 0) -> 1; -pow(A, 1) -> A; -pow(A, B) -> pow(A, B, 1). - -pow(_, 0, R) -> R; -pow(A, B, R) when B rem 2 == 0 -> pow(A * A, B bsr 1, R); -pow(A, B, R) -> pow(?MUL(A, A), B bsr 1, ?MUL(R, A)). +pow(A, B) -> ecu_misc:exp_mod(A, B, ?P). %% Arithmetics in prime field P f_add(A, B) -> (A + B) rem ?P. @@ -94,8 +88,7 @@ f_sub(A, B) -> (A - B + ?P) rem ?P. f_div(A, B) -> f_mul(A, f_inv(B)). f_inv(A) -> - {1, S, _T} = ecu_misc:eea(A, ?P), - (S + ?P) rem ?P. + pow(A, ?P - 2). %% Arithmetics in curve group order N s_add(A, B) -> (A + B) rem ?N.