在Python2.7中,长整数在给大数加幂之后是错误的

2024-06-07 12:35:09 发布

您现在位置:Python中文网/ 问答频道 /正文

计算RSA公钥和私钥时

幂是一个大数,而四舍五入的结果是长整数也是错误的

from fractions import gcd
def doLoop(e, totient):
    v = 0
    i = 1
    x = 0
    vv = 0
    while vv == 0:
        x = (e * i - 1) % totient
        if x == 0:
            v = i
            vv = 1
        i = i + 1
    return v

primeX = 3
primeY = 11
n = primeX*primeY
totient = (primeX - 1) * (primeY - 1)
e = 17
privatekey = doLoop(e, totient)
m = 9
encryptedvalue = int(int(math.pow(m,e)) % n)
int(math.pow(encryptedvalue,privatekey)) % n


>>> m
9
>>> e
17
>>> n
33
>>> int(math.pow(m,e)) % n
14L

应该是15到14岁

长整数错误

>>> int(round(math.pow(m,e)))
16677181699666568L

舍入数也是错误的

应该是

16677181699666569

enter image description here


Tags: 错误整数mathrsaint私钥公钥vv
1条回答
网友
1楼 · 发布于 2024-06-07 12:35:09

可以确认。。。但这里有一些解决办法。。你知道吗

>>> int(math.pow(9,17)) 
16677181699666568 
>>> 9**17 
16677181699666569 
>>> pow(9, 17)
16677181699666569
>>>
math.pow(x, y)
Return x raised to the power y. Exceptional cases follow Annex ‘F’ of the C99 standard as far as possible. In particular, pow(1.0, x) and pow(x, 0.0) always return 1.0, even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x, y) is undefined, and raises ValueError.

Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use ** or the built-in pow() function for computing exact integer powers.

Changed in version 2.6: The outcome of 1**nan and nan**0 was undefined.

相关问题 更多 >

    热门问题