I am implementing my own RSA algorithm in ruby to learn more about the algorithm.
It is almost working, but when I decrypt it a few numbers don’t decrypt but most do.
Why would this be?
For the given plaintext:
[ 42, 24, 424, 224, 421, 321]
The ciphertext is:
[1239,1263,1495,1349,208,1878]
Which when decrypted is:
[42,690,424,779,421,321]
This is the problem. Why is it happening?
These values are used to produce the keys (The method call is at the end of the program)
p = 51
q = 37
e = 223
n = 1887
phiN = 1800 (coprime with d)
d = 1687
class RSA
#edited to be concise, such as omitting initialize()
def encrypt(plainText)
index = 0
puts 'encrypt in is ', plainText
plainText.each do |i|
plainText[index] = ((i**(@e)) % @n )
index+=1
end
puts 'ciphertext is '
puts plainText
return plainText
end
def decrypt(cipherText)
puts 'decrypt in is ', cipherText
index = 0
cipherText.each do |i|
cipherText[index] = ((i**(@d)) % @n )
index+=1
end
puts 'plaintext is '
puts cipherText
return cipherText
end
def calcD()
@d=1
begin
s = (@d*@e)% @phiN;
@d+=1
end while not s==1
@d -= 1
#puts 'd is ', @d
end
end # class
message = RSA.new(51,37,223,[ 42, 24, 424, 224, 421, 321])
51 is not a prime.
Since that is one of the assumptions for the RSA algorithm, it should be no surprise that it fails to work.
Since your p is not a prime phi(n)!=(p-1)(q-1).
You could make it work by noticing that phi(51*37)=phi(3*17*37)=(3-1)(17-1)(37-1)=1152 and then calculating a working d=e^-1 (mod phi(n)) = 223^-1 (mod 1152) = 31, but I would recommend just using a prime p instead.