RSA是目前最有影響力的公鑰加密算法,它能夠抵抗到目前為止已知的絕大多數密碼攻擊,已被ISO推薦為公鑰數據加密標準。
今天只有短的RSA鑰匙才可能被強力方式解破。到2008年為止,世界上還沒有任何可靠的攻擊RSA算法的方式。只要其密鑰的長度足夠長,用RSA加密的信息實際上是不能被解破的。但在分布式計算和量子計算機理論日趨成熟的今天,RSA加密安全性受到了挑戰。
RSA算法基于一個十分簡單的數論事實:將兩個大素數相乘十分容易,但是想要對其乘積進行因式分解卻極其困難,因此可以將乘積公開作為加密密鑰。
核心代碼:
1
|
# -*- encoding:gbk -*- import math,random#導入模塊 def prime_num(max_num):#生成小于max_num的素數列表 prime_num=[] for i in xrange(2,max_num): temp=0 sqrt_max_num=int(math.sqrt(i))+1 for j in xrange(2,sqrt_max_num): if i%j==0: temp=j break if temp==0: prime_num.append(i) return prime_num def rsa_key():#生成密鑰的函數 prime=prime_num(400)#小于400的素數列表 p=random.choice(prime[-50:-1])#從后50個素數中隨機選擇一個作為p q=random.choice(prime[-50:-1])#從后50個素數中隨機選擇一個作為q while(p==q):#如果p和q相等則重新選擇 q=random.choice(prime[-50:-1]) N=p*q r=(p-1)*(q-1) r_prime=prime_num(r) e=random.choice(r_prime)#隨機選一個素數 d=0 for n in xrange(2,r): if (e*n)%r==1: d=n break return ((N,e),(N,d)) def encrypt(pub_key,origal):#生成加密用的公鑰 N,e=pub_key return (origal**e)%N def decrypt(pri_key,encry):#生成解密用的私鑰 N,d=pri_key return (encry**d)%N |
下面一段代碼給大家介紹python_rsa加密解密
使用python進行rsa加密與加密,包括公鑰加密私鑰解密,私鑰加密公鑰解密。(需要安裝M2Crypto庫)。
代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#!/usr/bin/env python #encoding=utf-8 ''' 測試rsa加密解密 ''' from M2Crypto import RSA msg = 'aaaa-aaaa' rsa_pub = RSA.load_pub_key( 'rsa_pub.pem' ) rsa_pri = RSA.load_key( 'rsa_pri.pem' ) print '*************************************************************' print '公鑰加密,私鑰解密' ctxt = rsa_pub.public_encrypt(msg, RSA.pkcs1_padding) ctxt64 = ctxt.encode( 'base64' ) print ( '密文:%s' % ctxt64) rsa_pri = RSA.load_key( 'rsa_pri.pem' ) txt = rsa_pri.private_decrypt(ctxt, RSA.pkcs1_padding) print ( '明文:%s' % txt) print '*************************************************************' print '私鑰加密,公鑰解密' ctxt_pri = rsa_pri.private_encrypt(msg, RSA.pkcs1_padding) ctxt64_pri = ctxt.encode( 'base64' ) print ( '密文:%s' % ctxt64_pri) txt_pri = rsa_pub.public_decrypt(ctxt_pri, RSA.pkcs1_padding) print ( '明文:%s' % txt_pri) |
庫的安裝說明
M2Crypto庫的下載地址:
https://github.com/martinpaljak/M2Crypto
或者:https://pypi.python.org/pypi/M2Crypto
依賴的庫:openssh-devel gcc swig (這3個庫在centos上可以直接使用yum安裝)