ruby RSA 算法有效 - 大多数情况下
我正在 ruby 中实现我自己的 RSA 算法,以了解有关该算法的更多信息。 它几乎可以工作,但是当我解密它时,一些数字没有解密,但大多数都可以。 为什么会这样呢?
对于给定的明文: [ 42, 24, 424, 224, 421, 321]
密文是: [1239,1263,1495,1349,208,1878]
解密后为: [42,690,424,779,421,321]
这就是问题所在。为什么会发生这种情况?
这些值用于生成键(方法调用位于程序末尾)
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])
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])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
51 不是素数。
由于这是 RSA 算法的假设之一,因此它失败也就不足为奇了。
因为你的 p 不是素数 phi(n)!=(p-1)(q-1)。
您可以通过注意到 phi(51*37)=phi(3*17*37)=(3-1)(17-1)(37-1)=1152 然后计算工作 d=e^ 来使其工作-1 (mod phi(n)) = 223^-1 (mod 1152) = 31,但我建议只使用素数 p 代替。
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.