RSA algorithm for image encryption
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
c
lc;
clear all;
format longE
disp('RSA algorithm');
p=input('Enter the prime no. for p: ');%23
q=input('Enter the prime no. for q: ');%13
n=p*q;
fprintf('\n n=%d',n);
phi=(p-1)*(q-1);
fprintf('\n phi(%d) = %d',n,phi);
e=input('\n Enter the value for e relatively prime to phi:');%23
%% find inverse for e
for d=1:phi
f=mod(e*d,phi);
if f==1
break
end
end
c=[2 254 123;214 231 189;241 253 3]% image matrix
A=[];
B=[];
%% cipher image
for i=1:3
for j=1:3
A(i,j)=mod(c(i,j)^(e),n);
end
end
%% decrypted image
for i=1:3
for j=1:3
B(i,j)=mod(A(i,j)^(d),n);
end
end
1 comentario
Ameer Hamza
el 5 de Sept. de 2020
This question might not be appropriate for this forum: https://www.mathworks.com/matlabcentral/answers/438831-is-discussion-of-cryptography-allowed
Respuestas (1)
Madhu
el 21 de Feb. de 2024
Editada: Walter Roberson
el 21 de Feb. de 2024
still you have the same doubt? Follow this code as it is.
img=imread('Lenna.jpg'); %Reading an RGB image
img=rgb2gray(img); % converting RBG image into grayscale image
img=imresize(img,[128,128]); % Resizing the image
img=reshape(img,1,numel(img)); % Reshaping 2D array into 1D array
img=double(img);
cip=zeros(1,numel(img));
ct=zeros(1,numel(img));
primenumbers=primes(1000);
p=primenumbers(randi(numel(primenumbers),1,1));
q=primenumbers(randi(numel(primenumbers),1,1));
n=p*q;
phi=(p-1)*(q-1);
e = randi([2, phi-1]);
while (gcd(e,phi)~=1)
x = randi([2, phi-1]);
if gcd(x, phi) == 1
e = x;
end
end
d=multiplicativeInverse(e, phi);
for i=1:1:numel(img)
cip(i)=powermod(img(i),e,n);
ct(i)=mod(cip(i),255); %Limiting cip to values less than 255.
end
ct=reshape(ct,128,128);
imshow(ct,[]);
pt=zeros(1,numel(img));
for i=1:1:numel(img)
pt(i)=powermod(cip(i),d,n);
end
pt=reshape(pt,128,128);
imshow(pt,[]);
function result = multiplicativeInverse(a, m)
[g, result, ~] = extended_gcd(a, m);
if g ~= 1
error('Inverse does not exist.');
end
result = mod(result, m);
end
function [g, x, y] = extended_gcd(a, b)
% Extended Euclidean Algorithm
if b == 0
g = a;
x = 1;
y = 0;
else
[g, x, y] = extended_gcd(b, mod(a, b));
temp = x;
x = y;
y = temp - floor(a/b) * y;
end
2 comentarios
Madhu
el 21 de Feb. de 2024
This code consists of both encryption and decryption of an image using RSA
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!