2010-07-22 4 views
4

RSA를 Python으로 구현하려고합니다. (물론 Python에 익숙하지 않습니다.) 물론 내가 작성한 코드는 4 자리 넘는 숫자에서는 작동하지 않습니다. 왜 이런 일이 일어나는 지 아십니까?Python에서 RSA 구현

p =0 
q=0 
n=0#modules 
phyPQ = 0 
e = 0 #public key exponent 
d = 0#private key exponent 
c = '' 
m = '' 

def getPrimes(): 
    global p 
    global q 
    p = long(raw_input("Enter first prime p : ")) 
    q = long(raw_input("Enter second prime q : ")) 

def computeModules(prime1, prime2): 
    global n 
    n = prime1 * prime2 
    print "Modules is = "+ `n` 
    return n 

def computePhyPQ(prime1, prime2): 
    global phyPQ 
    phyPQ = (prime1 -1) * (prime2 -1) 
    print "The phyPQ is " + `phyPQ` 

def computePublickeyExponent(x): 
    pubKeyExponentList= [] 
    for i in range(1, x): 
     if x % i != 0: 
      pubKeyExponentList.append(i) 
    print pubKeyExponentList 
    global e 
    e = long(raw_input("Pick a public key exponent from the list above : ")) 

def computePrivateKeyExponent(phyQP, pubKeyExpo): 
    flag = 1 
    count = 0 
    while flag == 1: 
     count = count + 1 
     if (count * phyQP + 1) % phyQP == 1: 
      result = (count * phyQP + 1)/float(pubKeyExpo) 
      if result % 1 == 0: 
       global d 
       d = long(result) 
       print 'The private key exponent exponent is:' + `d` 
       flag = 0 

def encryptMessage(exponent, modules): 
    #c= m ^e mod n 
    global c 
    message= long(raw_input("Enter a value to be encrypted:")) 

    c = long((message ** exponent) % modules) 
    print'The encrypted message is :' + `c` 

def decryptMessage(modules, privateKeyExpo, cryptedMessage): 
    #m = c^d % n 
    global m 
    m = (cryptedMessage ** privateKeyExpo) % modules 
    print 'message after decrypting is :' + `m` 

def mainMethod(): 
    getPrimes() 
    computeModules(p, q) 
    computePhyPQ(p, q) 
    computePublickeyExponent(phyPQ) 
    computePrivateKeyExponent(phyPQ, e) 
    encryptMessage(e, n) 
    decryptMessage(n, d, c) 

mainMethod() 
+1

당신이 * 필수입니다 건가요 * 다시 구현하려면? –

답변

4

귀하의 문제가 부동 소수점 연산의 사용의 가능성이 높습니다 조언하십시오

 result = (count * phyQP + 1)/float(pubKeyExpo) 

를이 알고리즘에서는 임의 정밀도 정수에 걸쳐 연산을 사용하는 것이 중요 할 것이다.

pow()의 세 인수 버전은 구현시 몇 군데에서 유용합니다. pow(x, y, z)은 임의 정밀도 정수의 경우 (x ** y) mod z을 계산합니다.

+1

사소한 단정 짓기 : 파이썬의'float' 타입은 실제적으로 두 배 (즉, 배정도 부동 소수점 산술)의 C'double'입니다. –

+1

@ Daniel Stutzbach : 고마워요. –

3

c = long((message ** exponent) % modules)은 매우 느리기 때문에 적절한 구현이 아닙니다.

제곱과 곱셈 지수, 슬라이딩 윈도우 지수, 또는 몽고메리 파워 리딩 래더로 바꿀 수 있습니다.

좋은 예

는 여기에서 찾을 수 있습니다 : 당신은 암호화를 위해 정상 수치 계산을 사용할 수 없습니다 http://code.activestate.com/recipes/572196-rsa/

0

.

결과 = (카운트 : 번호 통상적 1000 사용 파이썬 라이브러리 예, 변경,

수입 gmpy2 그런 큰 정수로 계산을 처리 할 수있는 등 gmpy2의 지수를 갖는다 * phyQP + 1)/플로트 (pubKeyExpo)

행 :

결과 = gmpy2.f_divmod (계산 * phyQP + 1, pubKeyExpo)

결과가 [0]> 0 결과 [1] == 0 경우 :