RSA Python和Extended Euclidean算法生成私钥。变量是无

问题描述 投票:0回答:3

简单的RSA加密算法的问题。 Extended Euclidean algorithm用于生成私钥。 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中的变量d = multiplicative_inverse(e, phi)包含None值,因此在加密期间我收到以下错误:

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

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

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


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

python python-3.x encryption rsa private-key
3个回答
1
投票

好吧,我不确定算法本身,并且无法判断你是否错误或正确,但你只能在multiplicative_inverse时从if temp_phi == 1函数返回一个值。否则,结果为None。所以我在你运行这个功能时打赌你的temp_phi != 1。函数的逻辑可能存在一些错误。


1
投票

我认为这是一个问题:

if temp_phi == 1:
   return d + phi

此函数仅在temp_phi等于1的条件下返回一些值,否则不返回任何值。


0
投票

这看起来就像是从python 2转换为3.在2中temp_phi / e将是一个整数,但在3中它是一个浮点数。由于多重反转分割方法使用整数,您需要将行更改为int(temp_phi / e)或temp_phi // e

© www.soinside.com 2019 - 2024. All rights reserved.