2011-11-02 110 views
3

我想在一次填充空格的時候使用Python對RSA加密一個單詞2個字符進行加密,但不知道如何去做。使用Python的RSA加密

例如,如果加密指數爲8,模數爲37329,單詞爲'Pound',我該如何去做?我知道我需要從pow(ord('P')開始,並且需要考慮到這個單詞是5個字符,我需要在一個空格處填充2個字符。我不確定,但是要做我還需要使用< < 8某處

謝謝

+0

請指出爲什麼你要用手而不是使用現有的庫。 – jfs

+0

@ J.F.Sebastian因爲我實際上並沒有學習Python語言,只是純粹將它用於加密,因爲這是我的焦點。我想要實現的現有庫的位置在哪裏? – Smush

+0

總的來說如果你不是自己編寫一個加密庫,也就是說,你只是在編寫一個加密的應用程序,那麼你應該與NIH綜合症作鬥爭,並使用現有的庫,特別是在加密等敏感領域。以下是與crypto相關的一些Python模塊的簡要比較:[python-crypto.pdf(2009)](http://webcache.googleusercontent.com/search?q=cache:BfEDT74QTawJ:mikeivanov.com/pc/python-crypto .pdf) – jfs

回答

3

這裏有一個基本的例子:

>>> msg = 2495247524 
>>> code = pow(msg, 65537, 5551201688147)    # encrypt 
>>> code 
4548920924688L 

>>> plaintext = pow(code, 109182490673, 5551201688147) # decrypt 
>>> plaintext 
2495247524 

見​​更多的工具與RSA風格公鑰加密的數學部分的工作。

字符如何打包和解壓縮成塊以及數字如何編碼的細節有點神祕。這是一個完整的工作RSA module in pure Python

爲特定的包裝模式(在一個時間2個字符,用空格填充),這應該工作:

>>> plaintext = 'Pound'  
>>> plaintext += ' '      # this will get thrown away for even lengths  
>>> for i in range(0, len(plaintext), 2): 
     group = plaintext[i: i+2] 
     plain_number = ord(group[0]) * 256 + ord(group[1]) 
     encrypted = pow(plain_number, 8, 37329) 
     print group, '-->', plain_number, '-->', encrypted 

Po --> 20591 --> 12139 
un --> 30062 --> 2899 
d --> 25632 --> 23784 
+1

謝謝,但如果我要在終端中完成上述操作,而不是在編輯器中編寫代碼,然後運行它,我將如何執行上述操作?出於興趣,它在那裏的256是什麼? – Smush

+1

乘以256與您最初考慮的「'8」相同。這是一種將兩個字節組合成小於32536的單個數字的方法。上面的代碼片段在終端中完成,而不是由編輯器創建的腳本完成。 –

+0

我真的會用指數運算的平方和乘法算法:http://en.wikipedia.org/wiki/Exponentiation_by_squaring – Nishant

1

如果你想使用Python來有效地編碼的RSA加密,我的github倉庫肯定會來理解和解釋RSA的數學定義在python

Cryptogrphic Algoritms Implementation Using Python

RSA密鑰生成

def keyGen(): ''' Generate Keypair ''' i_p=randint(0,20) i_q=randint(0,20) # Instead of Asking the user for the prime Number which in case is not feasible, # generate two numbers which is much highly secure as it chooses higher primes while i_p==i_q: continue primes=PrimeGen(100) p=primes[i_p] q=primes[i_q] #computing n=p*q as a part of the RSA Algorithm n=p*q #Computing lamda(n), the Carmichael's totient Function. # In this case, the totient function is the LCM(lamda(p),lamda(q))=lamda(p-1,q-1) # On the Contrary We can also apply the Euler's totient's Function phi(n) # which sometimes may result larger than expected lamda_n=int(lcm(p-1,q-1)) e=randint(1,lamda_n) #checking the Following : whether e and lamda(n) are co-prime while math.gcd(e,lamda_n)!=1: e=randint(1,lamda_n) #Determine the modular Multiplicative Inverse d=modinv(e,lamda_n) #return the Key Pairs # Public Key pair : (e,n), private key pair:(d,n) return ((e,n),(d,n))