2016-04-23 72 views
4

我一直在試圖找到編碼數字和解碼數字。我知道你需要找到這些基本規則,並開始嘗試創建一個python程序,它可以隨機選擇前150個素數來找到e變量和d變量。我這樣做的方式是:RSA編碼和解碼[e,d]。在python中查找e和d ..更新

import random 
from primesieve import * 
from sympy.solvers import * 
from sympy import * 
f = 0 
choiceOfPrimes = generate_primes(10) 

p = random.choice(choiceOfPrimes) 
q = random.choice(choiceOfPrimes) 

while p == q: 
    p = random.choice(choiceOfPrimes) 

n = p * q 
phiN = (p-1) * (q-1) 
lista = [] 
listb = [] 
for naa in range(1, phiN): 
    lista.append(naa) 
for naaa in range(1, 35): 
    listb.append(naaa) 

e = random.choice(lista) 


def finding_d(): 
    global phiN 
    global e 
    global f 
    f = e 
    abc = [] 
    abc = divmod(phiN, f) 
    abc1 = f * abc[0] 
    abc2 = abc[1] 
    phiN = f * abc1 + abc2 # phiN = f * {how many it goes in} + {remainder} 
    abc3 = divmod(f, abc2) 
    f = abc2 * abc3[0] + abc3[1] # (moved f to phiN) and (remainder to f) 
    abc4 = divmod(abc2, abc3[1]) 
    e1 = abc3[1] * abc4[0] 
    e2 = abc4[1] 
    abc2 = e1 + e2 
    e3 = abc2 + (e1*-1) # This bit I am struggling 





d = f 


while (e % n) == 0 and (e % phiN) == 0: 
    for r in range(phiN, 0, -1): 
     e = r 

while ((d * e) % phiN) != 1: 
    for r in range(1, 35): 
     e = r 

print(p, q, n, phiN, e, d) 

歷時永遠運行,並沒有完成運行。我甚至嘗試將generate_primes(150)更改爲generate_primes(10),但發生了同樣的問題。

有沒有人有解決方案,因爲我會很高興聽到它(順便說一句,primesieve庫不會自動在Python庫中,你必須自己下載它)。謝謝。

編輯:

我也做了: 而p ==問: P = random.choice(choiceOfPrimes) 但我有做的歐幾里德墊的困難的時候

+0

旁註:Python中的隨機模塊**不適合加密** – ppperry

+0

那麼,它在哪裏卡住了? –

回答

1

有一個很多與您的代碼的問題:

首先,

while p == q: 
    p = random.choice(choiceOfPrimes) 

在計算phiN的值之前,您應該執行此步驟,因爲如果更改p的值,phiN的值將會改變。


其次,

d = random.choice(lista) 

爲了計算d你應該對於發現的eModular multiplicative inversephiN使用Extended Euclidean algorithm,選擇的e直到他們的工作是非常低效的值。

+0

我將如何實現歐幾里德算法? – MeowWOW

+0

Rosetta Code有一個簡單的模塊化反轉實現:https://rosettacode.org/wiki/Modular_inverse#Python。 – uSeemSurprised

+0

現在'd'的值可以用上面代碼中的'modinv(e,phiN)'來計算。 – uSeemSurprised

相關問題