公鑰加密、私鑰解密
# -*- coding: utf-8 -*-
import rsa
# rsa加密
def rsaEncrypt(str):
# 生成公鑰、私鑰
(pubkey, privkey) = rsa.newkeys(512)
print("pub: ", pubkey)
print("priv: ", privkey)
# 明文編碼格式
content = str.encode('utf-8')
# 公鑰加密
crypto = rsa.encrypt(content, pubkey)
return (crypto, privkey)
# rsa解密
def rsaDecrypt(str, pk):
# 私鑰解密
content = rsa.decrypt(str, pk)
con = content.decode('utf-8')
return con
(a, b) = rsaEncrypt("hello")
print('加密后密文:')
print(a)
content = rsaDecrypt(a, b)
print('解密后明文:')
print(content)
密鑰導出、簽名驗證
# -*- coding: utf-8 -*-
import rsa
# 先生成一對密鑰,然后保存.pem格式文件,當然也可以直接使用
(pubkey, privkey) = rsa.newkeys(1024)
pub = pubkey.save_pkcs1()
pubfile = open('public.pem', 'wb')
pubfile.write(pub)
pubfile.close()
pri = privkey.save_pkcs1()
prifile = open('private.pem', 'wb')
prifile.write(pri)
prifile.close()
# load公鑰和密鑰
message = 'lovesoo.org'
with open('public.pem', "rb") as publickfile:
p = publickfile.read()
pubkey = rsa.PublicKey.load_pkcs1(p)
print(pubkey)
with open('private.pem', "rb") as privatefile:
p = privatefile.read()
privkey = rsa.PrivateKey.load_pkcs1(p)
print(privkey)
# 用公鑰加密、再用私鑰解密
crypto = rsa.encrypt(message.encode('utf-8'), pubkey)
message = rsa.decrypt(crypto, privkey)
message = message.decode('utf-8')
print (message)
# sign 用私鑰簽名認證、再用公鑰驗證簽名
signature = rsa.sign(message.encode('utf-8'), privkey, 'SHA-1')
method_name = rsa.verify('lovesoo.org'.encode('utf-8'), signature, pubkey)
print(method_name)
對文件進行RSA加密解密
from rsa.bigfile import *
import rsa
with open('public.pem') as publickfile:
p = publickfile.read()
pubkey = rsa.PublicKey.load_pkcs1(p)
with open('private.pem') as privatefile:
p = privatefile.read()
privkey = rsa.PrivateKey.load_pkcs1(p)
with open('mysec.txt', 'rb') as infile, open('outputfile', 'wb') as outfile: #加密輸出
encrypt_bigfile(infile, outfile, pubkey)
with open('outputfile', 'rb') as infile2, open('result', 'wb') as outfile2: #解密輸出
decrypt_bigfile(infile2, outfile2, privkey)
4.0的主要變化
版本3.4是3.x范圍內的最后一個版本。版本4.0刪除了以下模塊,因為它們不安全:
rsa._version133
rsa._version200
rsa.bigfile
rsa.varblock
這些模塊在3.4版中被標記為已棄用。
此外,在4.0中,I / O函數經過簡化,可以在所有支持的Python版本上使用字節。
4.0版本不再支持Python 2.6和3.3。