Search code examples
pythonrsaexponentiation

Different available sizes for Float and Integer in python


I've read some similar posts and the solution which you sugest is Decimal module. But my problem isn't that my code can't count it. I mean once it can and once not. Im interested in RSA and learning encryption and decryption private keys there is simple code:

p=53 #secret
q=59 #secret
n=p*q
k=2 #secret
print(n)
PHI=(p-1)*(q-1) #secret
print(PHI) #secret
#choose a small public exponent, "e" must be odd, have no common divisors with phi (n)
e=3
d=(k*PHI+1)/3 #secret
print(d) #secret
# secret message is 89
c=(89**e)%n
print(c)
x=(c**d)
print(x)
x=x%n
print(x)
"""x=1394**2011
print(x)"""

There is no problem with counting ((89^3) mod n) and there is no problem with last equation (as a comment) 1394^2011= i have number with 6324 digits, but when i try use x=(c^d) mod n i have :

Traceback (most recent call last):
  File "RSA.py", line 77, in <module>
    x=(c**d)
OverflowError: (34, 'Numerical result out of range')

Solution

  • e is an int, and so 89**e can be arbitrarily large (though I would use pow(89, e, n) so that you don't have to compute the large intermediate value 89**e first).

    d, however, is a float, and c**d will also be a float. A float cannot grow arbitrarily large, hence the error.

    Since d is supposed to be an int, use floored division.

    d = (k*PHI + 1) // 3