【发布时间】:2017-06-20 23:05:15
【问题描述】:
我正在尝试在 Python 中创建一个简单版本的 RSA,但是 - 无论是由于 Python 整数的限制还是我糟糕的代码 - 它都没有返回与原始消息相同的解密消息。我的密钥生成器似乎确实创建了有效的密钥,所以我很好奇它是如何失败的。
附件是我使用的代码 - 我认为它足够短,不需要添加存根。
from random import randint
from math import sqrt, ceil
#This is the private key the bank uses
bankPrime = 6619319052850372576671203008980947142174030778088896832879139788043990604607
#This is the public key
clientPrime = 89981040860183284202926925086489690550566335265876097787978356913003610730551
#Calculate modulus
modulus = bankPrime * clientPrime
#Calculate totient of modulus
totient = (bankPrime - 1)*(clientPrime - 1)
#Creates random numbers until it passes Euclid's algorithm with the GCD being 1 - coprime generator
def xgcd(b, n):
x0, x1, y0, y1 = 1, 0, 0, 1
while n != 0:
q, b, n = b // n, n, b % n
x0, x1 = x1, x0 - q * x1
y0, y1 = y1, y0 - q * y1
return b, x0
while True:
pubkeyexponent = randint(3, ceil(sqrt(totient)))
gcd, prikeyexponent = xgcd(pubkeyexponent, totient)
if prikeyexponent < 0:
prikeyexponent += totient
if gcd == 1:
break
print("Totient n", totient)
print("Private Key d", prikeyexponent)
print("Public Key e", pubkeyexponent)
print("Modulus", modulus)
print()
print("Type the message you want to encrypt:")
message = input(">:")
encrypted = 0
for x in range(len(message)):
encrypted += (256**x) * ord(message[x])
print(encrypted)
networkmessage = pow(encrypted, pubkeyexponent, totient)
print("The number message sent over the network to the bank is this:", networkmessage)
encrypted = pow(networkmessage, prikeyexponent, totient)
print("The number message sent back to the client is this:", encrypted)
【问题讨论】:
-
pow(encrypted, pubkeyexponent, totient)和pow(networkmessage, prikeyexponent, totient)使用了错误的模数。在这些行中将totient替换为modulus。 -
迟到总比不到好 - 谢谢!
标签: python python-3.x encryption rsa