繁体   English   中英

RSA Python和扩展欧几里得算法来生成私钥。 变量为无

[英]RSA Python & Extended Euclidean algorithm to generate the private key. Variable is None

简单的RSA加密算法存在问题。 扩展欧几里得算法用于生成私钥 multiplicative_inverse(e, phi)方法有关的问题。 它用于查找两个数字的乘法逆。 该函数不能正确返回私钥。 它返回None值。


我有以下代码:

import random

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

#Euclidean extended algorithm for finding the multiplicative inverse of two numbers
def multiplicative_inverse(e, phi):
    d = 0
    x1 = 0
    x2 = 1
    y1 = 1
    temp_phi = phi

    while e > 0:
        temp1 = temp_phi/e
        temp2 = temp_phi - temp1 * e
        temp_phi = e
        e = temp2

        x = x2- temp1* x1
        y = d - temp1 * y1

        x2 = x1
        x1 = x
        d = y1
        y1 = y

    if temp_phi == 1:
        return d + phi

def generate_keypair(p, q):
    n = p * q

    #Phi is the totient of n
    phi = (p-1) * (q-1)

    #An integer e such that e and phi(n) are coprime
    e = random.randrange(1, phi)

    #Euclid's Algorithm to verify that e and phi(n) are comprime
    g = gcd(e, phi)
    while g != 1:
        e = random.randrange(1, phi)
        g = gcd(e, phi)

    #Extended Euclid's Algorithm to generate the private key
    d = multiplicative_inverse(e, phi)

    #Public key is (e, n) and private key is (d, n)
    return ((e, n), (d, n))


if __name__ == '__main__':
    p = 17
    q = 23

    public, private = generate_keypair(p, q)
    print("Public key is:", public ," and private key is:", private)

由于以下行d = multiplicative_inverse(e, phi)中的变量d包含None值,因此在加密期间我收到以下错误:

TypeError: pow()不支持的操作数类型:'int','NoneType','int'

我在问题中提供的代码的输出:

公钥为:(269,391),私钥为:(无,391)


问题:为什么变量包含None值。 如何解决?

好吧,我不确定算法本身,也无法确定算法是对还是错,但是当if temp_phi == 1时,您只能从multiplicative_inverse函数返回一个值。 否则,结果为无。 所以我打赌您在运行该函数时temp_phi != 1 函数的逻辑中可能存在一些错误。

我认为这是一个问题:

if temp_phi == 1:
   return d + phi

该函数仅在temp_phi等于1的条件下才返回某个值,否则它将不返回任何值。

看起来您正在从python 2转换为3。在2中,temp_phi / e是整数,但在3中,它是浮点数。 由于多级除法使用整数,因此您需要将行更改为int(temp_phi / e)或temp_phi // e

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM