RSA algorithm for image encryption

13 views (last 30 days)
Parveiz Lone
Parveiz Lone on 5 Sep 2020
Edited: Walter Roberson on 21 Feb 2024
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

Answers (1)

Madhu
Madhu on 21 Feb 2024
Edited: Walter Roberson on 21 Feb 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 Comments
Madhu
Madhu on 21 Feb 2024
This code consists of both encryption and decryption of an image using RSA
Madhu
Madhu on 21 Feb 2024
Further any doubts mail me to msnaidu417@gmail.com

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!