RSA algorithm for image encryption
조회 수: 5 (최근 30일)
이전 댓글 표시
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
Ameer Hamza
2020년 9월 5일
This question might not be appropriate for this forum: https://www.mathworks.com/matlabcentral/answers/438831-is-discussion-of-cryptography-allowed
답변 (1개)
Madhu
2024년 2월 21일
편집: Walter Roberson
2024년 2월 21일
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
Kajal Chawla
2025년 7월 15일
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?
참고 항목
카테고리
Help Center 및 File Exchange에서 Encryption / Cryptography에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!