Improve pow by using crypto:mod_pow
This commit is contained in:
parent
68b4456469
commit
2680665593
@ -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;
|
||||
|
@ -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.
|
||||
|
Loading…
x
Reference in New Issue
Block a user