简体   繁体   中英

Python RSA Decryption is throwing TypeErrors

My RSA decrypt function:

def decrypt(ctext,private_key):
    key,n = private_key
    text = [chr(pow(char,key)%n) for char in ctext]
    return "".join(text)

is sometimes throwing a TypeError which tells that pow(char,key)%n provides a float . Why is that? I cant explain it myself and it would be interesting to know why.

For example it happens when:

ctext = [513300, 369218, 473524, 473524, 500307, 509880, 264366, 500307, 337068, 473524, 264834]
private_key = [-159317, 540767]

It's hard to figure out much from a tiny fragment of code. You are getting float results because your variable key is negative number. It is clear from the description of 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 standardRSA math you can always make your exponent positive by adding an appropriate multiple of Φ(n). In your particular case, Φ(n) = (631 - 1) * (857 - 1) = 539280, so key = 379963 mod Φ(n).

You should correct the code that gives you a negative exponent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM