Reputation: 41
I am trying to write a code for RSA Algorithm, my code produce (e,d,n) correctly, but the problem occurs when i calculate the cipher. cipher = (plain^e) mod n. because (plain^e) is a very large number. the Calculator gives my correct result, while Matlab Don't. any one have ideas?
clc
e=61;
d=21;
n= 187;
Neuler=160;
Plain='ABCD';
Plain=uint64(Plain);
%%Encrypting Progress
for i=1:length (Plain);
Cypher(i)=mod((Plain(i)^e),n);
end
Numeri_Cypher=uint64(Cypher);
for i=1:length (Numeri_Cypher);
RPlain(i)=mod((Numeri_Cypher(i)^d),n);
end
Result=char(RPlain)
Upvotes: 1
Views: 86
Reputation: 10792
The built-in function mod
can't deal with big integer. So I created a small implementation of the modular exponentiation, if you use this function you should have no problem.
function result = modpow(base,exp,m)
result = 1;
while (exp > 0)
if bitand(exp,1) > 0
result = mod((result * base),m);
end
exp = bitshift(exp,-1);
base = mod(base^2,m);
end
end
EXAMPLE:
With the built-in mod function:
mod(3^233249,4)
ans = 0 %incorrect result
With the modpow function
modpow(3,233249,4)
ans = 1 %correct result
Upvotes: 2