下面的代码完成了这项工作,在 wolfram 页面中缺少的是您必须选择大于 2 且小于 phi 的解决方案,然后只有一个解决方案。
[编辑]添加一个测试来检测 M 和 C 何时不是相对素数,然后返回一个比之前报告的算术错误更明确的错误元组
-module (decod).
-export ([private/2]).
% In the key generation you start by choosing P and Q 2 big primes
% N = P*Q
% M = (P-1)*(Q-1)
% C a number smaller than M such as gcd(M,C) = 1
% the public key is made of {N,C}
% then lets find U and V such as C*U + M*V = 1 and 2 < U < M
% the private key is {U,N}
private(M,C) when is_integer(M), is_integer(C), M > C->
P = private1({M,0},{C,1}),
adjust(P,M).
private1(_,{1,P}) -> P;
private1(_,{0,_}) -> {error,gcd_not_1};
private1({R1,U1},{R2,U2}=A2) ->
F = R1 div R2,
private1(A2,{R1-R2*F,U1-U2*F}).
adjust(R,_) when is_tuple(R) ->
R;
adjust(P1,M) when P1 =< 2 ->
K = (2 - P1) div M + 1,
P1 + K * M;
adjust(P1,M) when P1 >= M ->
K = (P1 - M) div M + 1,
P1 - K * M;
adjust(P1,_) -> P1.