2016-09-24 3 views
0

단순한 RSA 암호화 알고리즘에 문제가 있습니다. Extended Euclidean algorithm개인 키을 생성하는 데 사용됩니다. multiplicative_inverse(e, phi) 메소드의 문제점. 이것은 두 숫자의 곱셈 역함수를 찾는 데 사용됩니다. 이 함수는 개인 키를 올바르게 반환하지 않습니다. None 값을 반환합니다.개인 키를 생성하는 RSA Python 및 확장 유클리드 알고리즘. 변수는 없음


I가 다음 코드를 가지고

TypeError: unsupported operand type(s) for pow(): 'int', 'NoneType', 'int'

출력 다음 줄 d = multiplicative_inverse(e, phi)에서 변수 d 때문에

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) 

None 값 후 암호화 과정 I는 다음과 같은 오류가 나타날 포함 질문에서 제공 한 코드는 다음과 같습니다.

Public key is: (269, 391) and private key is: (None, 391)


질문 : 변수가 None 값을 포함하는 이유. 그것을 고치는 방법?

+1

[모듈러 구조의 곱셈 역수 계산] (https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Computing_multiplicative_inverses_in_modular_structures)에 대한 의사 코드는 비교적 간단하고 Python에 매핑하기 쉽습니다. 다시 볼 것을 제안합니다. 당신이 만든 많은 실수가 있습니다. 'else' 브랜치에서 유용한 것을 반환하는 것을 잊어 버리는 것은 문제의 시작일뿐입니다. –

답변

1

글쎄, 알고리즘 자체에 대해 잘 모르겠다. 만약 그것이 틀렸거나 옳은지를 알 수는 없지만 multiplicative_inverse 함수의 값을 if temp_phi == 1으로 돌려 주면된다. 그렇지 않으면 결과는 없음입니다. 그래서 당신이 temp_phi != 1 때 함수를 실행 내기. 함수의 논리에 실수가있을 수 있습니다. 그렇지 않으면 모든 값을 반환하지 않습니다,

if temp_phi == 1: 
    return d + phi 

이 기능은 temp_phi 1 같다는 것을 조건에서 어떤 값을 반환 :

1

나는 이것이 문제라고 생각합니다.

관련 문제