问题
I have two numbers, p
, and q
. I know that I can get phi = (p-1)*(q-1)
and that ed = 1 (mod phi)
... but I'm not sure I get what this means.
I wrote some Python:
p = NUM
q = NUM
e = NUM
phi = (p-1)*(q-1)
d = (1 % phi)/float(e)
But I always get a decimal, and d
is supposed to be an integer. what am I doing wrong?
EDIT: I may just not understand RSA. Right now, I'm looking at this page: http://www.di-mgt.com.au/rsa_alg.html
回答1:
Your understanding of the math is wrong. The equation
ed ≡ 1 (mod φ)
means that, the remainder of number ed dividing φ is equal to 1, i.e. in terms of Python,
>>> (e*d) % phi
1
For instance, if φ = (7 - 1)(11 - 1) = 60, and e = 17, then if we choose d = 53, then we'll get
>>> e = 17
>>> d = 53
>>> phi = 60
>>> (e*d) % phi
1
We call d a modular multiplicative inverse of e.
To generate d from e and φ, usually extended Euclidean algorithm is used. Please read http://en.wikipedia.org/wiki/Modular_multiplicative_inverse or https://stackoverflow.com/search?q=python+%22multiplicative+inverse%22&submit=search for more info
回答2:
Since the dnominator on the division is a float, Python will always promote the result of the division to a float.
If you want to explictely have the result as an integer, do not promote any of the operators to float, and use the "//" operator instead - it prevents, in a "future compatible" way, automatic conversion of the division result to a float.
d = (1 % phi)// e
回答3:
It's returning a decimal because you're dividing by a floating point number
float(e)
You can get the final number to be converted into an integer by wrapping the whole computation in an int() function like this :
d = int( (1 mod phi)/float(e) )
来源:https://stackoverflow.com/questions/8884076/programmatically-generate-d-from-p-and-q-rsa