(RSA)我退出stackoverflow的此脚本返回负d值

时间:2018-10-07 08:26:30

标签: python cryptography rsa

所以我偶然用此脚本在此线程上运行,它返回一个负的d值,而我的p和q值都是素数。有什么原因吗?可能只是错误的脚本?

def egcd(a, b):
    x,y, u,v = 0,1, 1,0
    while a != 0:
        q, r = b//a, b%a
        m, n = x-u*q, y-v*q
        b,a, x,y, u,v = a,r, u,v, m,n
        gcd = b
    return gcd, x, y

def main():

    p = 153143042272527868798412612417204434156935146874282990942386694020462861918068684561281763577034706600608387699148071015194725533394126069826857182428660427818277378724977554365910231524827258160904493774748749088477328204812171935987088715261127321911849092207070653272176072509933245978935455542420691737433
    q = 156408916769576372285319235535320446340733908943564048157238512311891352879208957302116527435165097143521156600690562005797819820759620198602417583539668686152735534648541252847927334505648478214810780526425005943955838623325525300844493280040860604499838598837599791480284496210333200247148213274376422459183
    e = 65537
    ct = 313988037963374298820978547334691775209030794488153797919908078268748481143989264914905339615142922814128844328634563572589348152033399603422391976806881268233227257794938078078328711322137471700521343697410517378556947578179313088971194144321604618116160929667545497531855177496472117286033893354292910116962836092382600437895778451279347150269487601855438439995904578842465409043702035314087803621608887259671021452664437398875243519136039772309162874333619819693154364159330510837267059503793075233800618970190874388025990206963764588045741047395830966876247164745591863323438401959588889139372816750244127256609

    # compute n
    n = p * q

    # Compute phi(n)
    phi = (p - 1) * (q - 1)

    # Compute modular inverse of e
    gcd, a, b = egcd(e, phi)
    d = a

    print( "n:  " + str(d) );

    # Decrypt ciphertext
    pt = pow(ct,d,n)
    print( "pt: " + str(pt) )

if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:1)

可能会发生这种情况,下面我将解释原因,但出于实际目的,您将想知道如何解决它。答案是将phi添加到d并使用该值:一切都会按照RSA的要求进行。

那为什么会发生呢?该算法计算扩展的gcd。 egcd的结果为a*e + b*phi = gcd,对于RSA,为gcd = 1,所以a*e + b*phi = 1

如果以phi为模(这是乘法组的阶)看待这个方程,那么a*e == 1 mod phi就是使RSA工作所需的条件。实际上,通过相同的等价关系,您可以将phi的任意倍数加到a上,并且等价关系仍然成立。

现在再次查看方程式:a*e + b*phi = 1。我们知道ephi是正整数。您不能在此等式中拥有所有正整数,否则它的总和将不会等于1(它将远大于1)。因此,这意味着ab将为负数。有时是a为负数,有时是b。当它是b时,您的a就会出现:您将其分配给值d的正整数。但是其他时候,您对a的使用是负值。我们不想要那样,因此只需在其中添加phi并使其值为d