RSA algorithm for image encryption

5 visualizzazioni (ultimi 30 giorni)
Parveiz Lone
Parveiz Lone il 5 Set 2020
Commentato: Kajal Chawla il 15 Lug 2025
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

Risposte (1)

Madhu
Madhu il 21 Feb 2024
Modificato: Walter Roberson il 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
  3 Commenti
Madhu
Madhu il 21 Feb 2024
Further any doubts mail me to msnaidu417@gmail.com
Kajal  Chawla
Kajal Chawla il 15 Lug 2025
Respected mam, I have gone through your code and have a doubt regarding decryption of this code. When a reciever wants to decrypt the image he has the access to encrypted image matrix that is ct, but decryption code needs the matrix cip. Can you please clarify that?

Accedi per commentare.

Categorie

Scopri di più su Encryption / Cryptography in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by