Improve pow by using crypto:mod_pow

This commit is contained in:
Hans Svensson 2022-01-17 12:20:58 +01:00
parent 68b4456469
commit 2680665593
2 changed files with 14 additions and 10 deletions

View File

@ -4,10 +4,21 @@
%%% Created : 13 Jan 2022 by Hans Svensson %%% Created : 13 Jan 2022 by Hans Svensson
-module(ecu_misc). -module(ecu_misc).
-export([eea/2, -export([eea/2, exp_mod/3,
hex_to_bin/1, bin_to_hex/1, hex_to_bin/1, bin_to_hex/1,
pcomp/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 %% Extended Euclidean Algorithm
eea(A, B) when ((A < 1) or (B < 1)) -> eea(A, B) when ((A < 1) or (B < 1)) ->
undefined; undefined;

View File

@ -79,13 +79,7 @@ p_add({X1, Y1}, {X2, Y2}) ->
Y3 = ?SUB(?MUL(M, ?SUB(X1, X3)), Y1), Y3 = ?SUB(?MUL(M, ?SUB(X1, X3)), Y1),
{X3, Y3}. {X3, Y3}.
pow(_, 0) -> 1; pow(A, B) -> ecu_misc:exp_mod(A, B, ?P).
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)).
%% Arithmetics in prime field P %% Arithmetics in prime field P
f_add(A, B) -> (A + B) rem ?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_div(A, B) -> f_mul(A, f_inv(B)).
f_inv(A) -> f_inv(A) ->
{1, S, _T} = ecu_misc:eea(A, ?P), pow(A, ?P - 2).
(S + ?P) rem ?P.
%% Arithmetics in curve group order N %% Arithmetics in curve group order N
s_add(A, B) -> (A + B) rem ?N. s_add(A, B) -> (A + B) rem ?N.