unit public_key;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Panel1: TPanel;
Label1: TLabel;
Edit1: TEdit;
Edit2: TEdit;
Button1: TButton;
Button2: TButton;
Edit3: TEdit;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
var
M:array of integer;
A:array of integer;
B:array of integer;
c,w_1,k:integer; //k>b1+b2+...+bn;
//w_1是w的逆;
implementation
{$R *.dfm}
Function judge_pri_num(p:integer):integer; //判断是否是素数;
var
l,i:integer;
begin
i:=2;
l:=0;
while(i<=Sqrt(strtofloat(inttostr(p)))) and (l=0) do
if p mod i=0 then l:=1 else i:=i+1;
judge_pri_num:=l;
end;
Function judge_twonum_prime(m,n:integer):integer; //判断两个数是否互素;
var
i,temp,p:integer;
begin
p:=0;
if m>n then //确定m<n,若m>n,则调换
begin
temp:=m;
m:=n;
n:=temp;
end;
for i:=2 to m do
if (m mod i=0) and (n mod i=0) then
p:=1; //说明m,n不互素;
judge_twonum_prime:=p;
end;
procedure produce_a(j:integer); //产生序列A[i];
var
i,m,n,w,w_1:integer;
begin
setlength(B,j-1);
setlength(A,j-1);
B[0]:=random(10);
for i:=1 to (j-1) do //产生随机的超递增序列B[i];
B[i+1]:=2*B[i]+random(100);
k:=2*B[j-1]+random(10);
repeat
w:=random(1000);
until judge_twonum_prime(k,w)=0;
m:=1;
repeat
n:=w*m;
m:=m+1;
until n mod k=1;
w_1:=n;
for i:=0 to (j-1) do
A[i]:=(B[i]*w) mod k; //将A[i]作为公钥;
end;
procedure TForm1.Button1Click(Sender: TObject); //加密过程;
var
s1:string;
i,j:integer;
begin
s1:=edit1.Text;
i:=length(s1); //No error;
//edit4.Text:=Copy(s1,0,1);
c:=0;
setlength(M,i-1);
for j:=0 to i-1 do
M[j]:=strtoint(Copy(s1,j,1));
//edit4.Text:=inttostr(M[1]);
produce_a(i);
for j:=0 to (i-1) do
c:=c+A[j]*M[j];
edit2.Text:=inttostr(c);
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
close;
end;
procedure TForm1.Button2Click(Sender: TObject); //解密过程;
var
i,j,m:integer;
s:string;
begin
s:='';
i:=(c*w_1) mod k;
j:=length(edit1.Text);
setlength(M,j-1);
for m:=0 to (j-1) do
M[m]:=0;
for m:=(j-1) to 0 do
begin
if B[m]<i then
begin
M[m]:=1;
i:=i-B[m];
end
end;
for m:=0 to (j-1) do
s:=s+'inttostr(M[m])';
edit3.Text:=s;
end;
end.