programmatically generate `d` from `p` and `q` (RSA)

孤街醉人 提交于 2019-12-08 04:26:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!