本文實例講述了Python實現(xiàn)的rsa加密算法。分享給大家供大家參考,具體如下:
算法過程
1. 隨意選擇兩個大的質(zhì)數(shù)p和q,p不等于q,計算N=pq。
2. 根據(jù)歐拉函數(shù),不大于N且與N互質(zhì)的整數(shù)個數(shù)為(p-1)(q-1)。
3. 選擇一個整數(shù)e與(p-1)(q-1)互質(zhì),并且e小于(p-1)(q-1)。
4. 用以下這個公式計算d:d× e ≡ 1 (mod (p-1)(q-1))。
5. 將p和q的記錄銷毀。
(N,e)是公鑰,(N,d)是私鑰。
python代碼
# -*- coding: utf-8 -*-#!/usr/bin/env pythondef range_prime(start, end): l = list() for i in range(start, end+1):  flag = True  for j in range(2, i):   if i % j == 0:    flag = False    break  if flag:   l.append(i) return ldef generate_keys(p, q): #numbers = (11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47) numbers =range_prime(10, 100) N = p * q C = (p-1) * (q-1) e = 0 for n in numbers:  if n < C and C % n > 0:   e = n   break if e==0:  raise StandardError("e not found") #Python3中改為BaseException d = 0 for n in range(2, C):  if(e * n) % C == 1:   d = n   break if d==0:  raise StandardError("d not found") return ((N, e), (N, d))def encrypt(m, key): C, x = key return (m ** x) % Cdecrypt = encryptif __name__ == '__main__': pub, pri = generate_keys(47, 79) L = range(20, 30) C = map(lambda x: encrypt(x, pub), L) D = map(lambda x: decrypt(x, pri), C) print "武林站長站測試結(jié)果:" print "keys:", pub, pri print "message:", L print "encrypt:", C print "decrypt:", D運行結(jié)果:

其實用什么語言實現(xiàn)這個過程都不是很麻煩,只是我們老師要求生成1024的隨機數(shù),用c語言寫就有點惡心了,所以用python或者java實現(xiàn)要更加方便一點。
PS:關(guān)于加密解密感興趣的朋友還可以參考本站在線工具:
文字在線加密解密工具(包含AES、DES、RC4等):
http://tools.jb51.net/password/txt_encode 
MD5在線加密工具:
http://tools.jb51.net/password/CreateMD5Password
在線散列/哈希算法加密工具:
http://tools.jb51.net/password/hash_encrypt
在線MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:
http://tools.jb51.net/password/hash_md5_sha
在線sha1/sha224/sha256/sha384/sha512加密工具:
http://tools.jb51.net/password/sha_encode
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python加密解密算法與技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
新聞熱點
疑難解答