1
%% ``The contents of this file are subject to the Erlang Public License,
2
%% Version 1.1, (the "License"); you may not use this file except in
3
%% compliance with the License. You should have received a copy of the
4
%% Erlang Public License along with this software. If not, it can be
5
%% retrieved via the world wide web at http://www.erlang.org/.
7
%% Software distributed under the License is distributed on an "AS IS"
8
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
9
%% the License for the specific language governing rights and limitations
12
%% The Initial Developer of the Original Code is Ericsson Utvecklings AB.
13
%% Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings
14
%% AB. All Rights Reserved.''
19
%%% Description: SSH math utilities
23
-export([ilog2/1, ipow/3, invert/2, ipow2/3]).
26
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
30
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
32
%% number of bits (used) in a integer = isize(N) = |log2(N)|+1
34
ssh_bits:isize(N) - 1.
37
%% calculate A^B mod M
38
ipow(A, B, M) when M > 0, B >= 0 ->
39
crypto:mod_exp(A, B, M).
41
ipow2(A, B, M) when M > 0, B >= 0 ->
48
ipow2(A, 1, M, Prod) ->
50
ipow2(_A, 0, _M, Prod) ->
52
ipow2(A, B, M, Prod) ->
56
ipow2(A1, B1, M, Prod);
58
ipow2(A1, B1, M, (A*Prod) rem M)
64
%% gcd(R, Q) when abs(Q) < abs(R) -> gcd1(Q,R);
65
%% gcd(R, Q) -> gcd1(R,Q).
73
%% %% Least common multiple of (R,Q)
78
%% (Q div gcd(R, Q)) * R.
81
%% %% Extended gcd gcd(R,Q) -> {G, {A,B}} such that G == R*A + Q*B
83
%% %% Here we could have use for a bif divrem(Q, R) -> {Quote, Remainder}
85
%% egcd(R,Q) when abs(Q) < abs(R) -> egcd1(Q,R,1,0,0,1);
86
%% egcd(R,Q) -> egcd1(R,Q,0,1,1,0).
88
%% egcd1(0,Q,_,_,Q1,Q2) -> {Q, {Q2,Q1}};
89
%% egcd1(R,Q,R1,R2,Q1,Q2) ->
91
%% egcd1(Q rem R, R, Q1-D*R1, Q2-D*R2, R1, R2).
94
%% Invert an element X mod P
95
%% Calculated as {1, {A,B}} = egcd(X,P),
96
%% 1 == P*A + X*B == X*B (mod P) i.e B is the inverse element
98
%% X > 0, P > 0, X < P (P should be prime)
100
invert(X,P) when X > 0, P > 0, X < P ->
110
inv(P rem X, X, Q1 - D*R1, R1).
114
%% %% Integer square root
119
%% isqrt(X) when X >= 0 ->
121
%% isqrt(X div R, R, X).
123
%% isqrt(Q,R,X) when Q < R ->
125
%% isqrt(X div R1, R1, X);
126
%% isqrt(_, R, _) -> R.