پنجشنبه, ۱۴ آذر ۱۳۹۸، ۱۰:۴۱ ق.ظ
کد الگوریتم RSA در متلب
دو عدد اول از شما درخواست می کنه، بعد از آماده سازی کلید های خصوصی و عمومی یک متن را از شما خواهد خواست یا اینکه شما می تونید با یک سری تغییراتی یک بردار عددی را مستقیما به الگوریتم تحویل بدید، چون متن در نهایت به کد اسکی اون تبدیل می شه، بعد الگوریتم، متن رمزگذاری شده و متن رمزگشایی شده را به همراه کد اسکی متن رمزگذاری شده و رمزگشایی شده به شما برمی گردونه...
clc;% clear theconsol
clear;%clear the memory and variables
delete(allchild(0)); %close all open diologs
file=matlab.desktop.editor.getActive;
try
fileDetail=dir(file.Filename);
folderName=fileDetail.folder;
catch
index=strfind( file.Filename,'\');
folderName=file.Filename(1:index(end)-1);
end
paths=genpath(folderName);
addpath(paths);
cd(folderName);
disp('RSA algorithm');
p=input('Enter the prime no. for p: ');
q=input('Enter the prime no. for q: ');
n=p*q;
fprintf('\nn=%d',n);
phi=(p-1)*(q-1);
fprintf('\nphi(%d) is %d',n,phi);
e=randsample( primes(n-1),1);
val1=0;
d=0;
while(val1~=1)
d=d+1;
val1=mod(d*e,phi);
end
fprintf('\nd=%d',d);
fprintf('\nPublic key is (%d,%d)',e,n);
fprintf('\nPrivate key is (%d,%d)',d,n);
m=input('\nEnter the message: ','s');
m1=m-0;
disp('ASCII equivalent of message ');
disp(m1);
over=length(m1);
o=1;
while(o<=over)
m=m1(o);
diff=0;
if(m>n)
diff=m-n+1;
end
m=m-diff;
% beacause matlab dont support larg number modulus operation then
% encription and deription is done in bit level
qm=dec2bin(e);
len=length(qm);
c=1;
xz=1;
while(xz<=len)
if(qm(xz)=='1')
c=mod(mod((c^2),n)*m,n);
elseif(qm(xz)=='0')
c=(mod(c^2,n));
end
xz=xz+1;
end
c1(o)=c;
c1(o)=mod(m^e ,n);
% nm2(o)=mod(c1(o)^d ,n)+diff;
% Public key is (e,n) => (7,33)
% Private key is (d,n) => (3,33)
% The encryption of m = 2 is c = 27 % 33 = 29
% The decryption of c = 29 id m =293 % 33 = 2
qm1=dec2bin(d);
len1=length(qm1);
nm=1;
xy=1;
while(xy<=len1)
if(qm1(xy)=='1')
nm=mod(mod((nm^2),n)*c,n);
elseif(qm1(xy)=='0')
nm=(mod(nm^2,n));
end
xy=xy+1;
end
nm=nm+diff;
nm1(o)=char(nm);
o=o+1;
end
o=1;
fprintf('\nThe encrypted message in ASCII is \n');
while(o<=over)
fprintf('\t%d',c1(o));
o=o+1;
end
o=1;
fprintf('\nThe encrypted message is \n');
disp(char(c1))
fprintf('\nThe decrypted message in ASCII is \n');
while(o<=over)
fprintf('\t%d',nm1(o));
o=o+1;
end
fprintf('\nThe decrypted message is: ');
disp(nm1);
fprintf('\n');
۹۸/۰۹/۱۴