Python RSA 解密抛出类型错误
Python RSA Decryption is throwing TypeErrors
我的RSA解密函数:
def decrypt(ctext,private_key):
key,n = private_key
text = [chr(pow(char,key)%n) for char in ctext]
return "".join(text)
有时会抛出一个 TypeError
,这表明 pow(char,key)%n
提供了一个 float
。这是为什么?我自己无法解释,知道为什么会很有趣。
例如,它发生在:
ctext = [513300, 369218, 473524, 473524, 500307, 509880, 264366, 500307, 337068, 473524, 264834]
private_key = [-159317, 540767]
很难从一小段代码中找出很多东西。您得到的是浮动结果,因为您的变量 key
是负数。从 pow that you will get float results, which is not what you want. You really should be using the 3-argument form of pow, and your exponent should always be positive. By using standard RSA math 的描述中可以清楚地看出,您始终可以通过添加 Φ(n) 的适当倍数使您的指数为正。在您的特定情况下,Φ(n) = (631 - 1) * (857 - 1) = 539280,因此 key = 379963 mod Φ(n)。
您应该更正给出负指数的代码。
我的RSA解密函数:
def decrypt(ctext,private_key):
key,n = private_key
text = [chr(pow(char,key)%n) for char in ctext]
return "".join(text)
有时会抛出一个 TypeError
,这表明 pow(char,key)%n
提供了一个 float
。这是为什么?我自己无法解释,知道为什么会很有趣。
例如,它发生在:
ctext = [513300, 369218, 473524, 473524, 500307, 509880, 264366, 500307, 337068, 473524, 264834]
private_key = [-159317, 540767]
很难从一小段代码中找出很多东西。您得到的是浮动结果,因为您的变量 key
是负数。从 pow that you will get float results, which is not what you want. You really should be using the 3-argument form of pow, and your exponent should always be positive. By using standard RSA math 的描述中可以清楚地看出,您始终可以通过添加 Φ(n) 的适当倍数使您的指数为正。在您的特定情况下,Φ(n) = (631 - 1) * (857 - 1) = 539280,因此 key = 379963 mod Φ(n)。
您应该更正给出负指数的代码。