Python如何基于rsa模塊實現(xiàn)非對稱加密與解密
這篇文章主要介紹了Python如何基于rsa模塊實現(xiàn)非對稱加密與解密,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
1、簡單介紹:
RSA加密算法是一種非對稱加密算法 是由已知加密密鑰推導(dǎo)出解密密鑰在計算上是不可行的”密碼體制。加密密鑰(即公開密鑰)PK是公開信息,而解密密鑰(即秘密密鑰)SK是需要保密的。
RSA密鑰至少為500位長,一般推薦使用1024位。RSA密鑰長度隨著保密級別提高,增加很快。
由于RSA的特性,一個1024位的密鑰只能加密117位字節(jié)數(shù)據(jù),當數(shù)據(jù)量超過117位字節(jié)的時候,程序就會拋出異常。 ——來自大佬
2、代碼實現(xiàn):
來一段大佬的代碼:
import rsa
# 一、生成公鑰及私鑰, 并保存
public_key, private_key = rsa.newkeys(1024) # 生成公鑰和私鑰
# 將生成的公鑰和私鑰進行轉(zhuǎn)換,以便存儲
pub = public_key.save_pkcs1()
pri = private_key.save_pkcs1('PEM') # save_pkcsl()是內(nèi)置方法,其默認參數(shù)是‘PEM'
with open('pubkey.pem', mode='wb') as f, open('privkey.pem', mode='wb') as f1:
f.write(pub) # 打開兩個文件,分別存儲公鑰及私鑰
f1.write(pri)
# 二. 使用公鑰加密, 私鑰解密
def func():
with open('pubkey.pem', mode='rb') as f, open('privkey.pem', 'rb') as f1:
pub = f.read() # 從文件中再讀出公鑰和私鑰
pri = f1.read()
public_key = rsa.PublicKey.load_pkcs1(pub) # 轉(zhuǎn)換為原始狀態(tài)
private_key = rsa.PrivateKey.load_pkcs1(pri)
message = "rsa加密測試"
info = rsa.encrypt(message.encode('utf-8'), public_key) # 使用公鑰加密內(nèi)容,內(nèi)容必須是二進制
msg = rsa.decrypt(info, private_key) # 使用私鑰解密,獲得解密后的內(nèi)容
print(msg.decode('utf-8')) # 使用之前記得先解碼
3、代碼升級:
現(xiàn)在我將上述的代碼段封裝成一個Rsa class(包含的方法有:__init__——初始化方法,key_transform_store——存儲公鑰與私鑰的方法、encry——加密方法、decry——解密方法),使用的時候,直接將下面的代碼段拎到我們需要的地方去引用:先創(chuàng)建一Rsa對象,然后調(diào)用里面的方法即可:
import rsa
class Rsa(object):
"""RSA加密、解密"""
def __init__(self, number, pub_path='public_key.pem', priv_path='private_key.pem'):
"""
:param pub_path: the path to public key, default its path is public_key.pem
:param priv_path: the path to private key, default its path is private_key.pem
"""
# Generate the public and private keys, and returns them
self.public_key, self.private_key = rsa.newkeys(number)
self.public_key_path = pub_path
self.private_key_path = priv_path
def key_transform_store(self):
"""
convert and save the generated public and private keys to a file
:return: None
"""
# convert the generated public and private keys for storage
pub = self.public_key.save_pkcs1()
pri = self.private_key.save_pkcs1('PEM')
# open two files to store the public key and private key respectively
with open(self.public_key_path, mode='wb') as f:
f.write(pub)
with open(self.private_key_path, mode='wb') as f1:
f1.write(pri)
def encry(self, info):
"""
encrypt information
:param info: the original string information to be encrypted
:return:info_encrypted
"""
# read the public key from the file
with open(self.public_key_path, mode='rb') as f:
pub = f.read()
# convert pub to original state
public_key = rsa.PublicKey.load_pkcs1(pub)
# use the public key to encrypt the content, which must be binary
info_encrypted = rsa.encrypt(info.encode('utf-8'), public_key)
return info_encrypted
def decry(self, info_encrypted):
"""
decrypt information
:param info_encrypted: encrypted information
:return: info
"""
# read the private key from the file
with open(self.private_key_path, 'rb') as f:
pri = f.read()
# convert pri to original state
private_key = rsa.PrivateKey.load_pkcs1(pri)
# decrypt with private key to obtain the decrypted content
msg = rsa.decrypt(info_encrypted, private_key)
info = msg.decode('utf-8') # decode
return info
rsa_obj = Rsa(1024) # 實例化
rsa_obj.key_transform_store() #
info_encrypted = rsa_obj.encry('我是真心喜歡你的。') # 加密
print(info_encrypted)
info = rsa_obj.decry(info_encrypted) # 解密
print(info) # 我是真心喜歡你的。
這里會出現(xiàn)一個問題:由于RSA的特性,一個1024位的密鑰只能加密117位字節(jié)數(shù)據(jù),當數(shù)據(jù)量超過117位字節(jié)的時候,程序就會拋出異常。如下測試會拋出:
OverflowError: 189 bytes needed for message, but there is only space for 117
rsa_obj = Rsa(1024) # 實例化
rsa_obj.key_transform_store() #
info_encrypted = rsa_obj.encry('我是真心喜歡你的。我是真心喜歡你的。我是真心喜歡你的。我是真心喜歡你的。我是真心喜歡你的。我是真心喜歡你的。我是真心喜歡你的。') # 加密
print(info_encrypted)
info = rsa_obj.decry(info_encrypted) # 解密
print(info)
后記: 通常使用中, 會先對數(shù)據(jù)進行bas64加密, 再對加密后的內(nèi)容使用rsa加密, 最后對rsa解密后的內(nèi)容進行bas64解密。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決python執(zhí)行不輸出系統(tǒng)命令彈框的問題
今天小編就為大家分享一篇解決python執(zhí)行不輸出系統(tǒng)命令彈框的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06
Python+Django+MySQL實現(xiàn)基于Web版的增刪改查的示例代碼
這篇文章主要介紹了Python+Django+MySQL實現(xiàn)基于Web版的增刪改查的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05
Python深度學習pytorch實現(xiàn)圖像分類數(shù)據(jù)集
這篇文章主要為大家講解了關(guān)于Python深度學習中pytorch實現(xiàn)圖像分類數(shù)據(jù)集的示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10
Python設(shè)計模式創(chuàng)建型原型模式
這篇文章主要介紹了Python原型模式,原型模式即Prototype?Pattern,指用原型實例指定創(chuàng)建對象的種類,并且通過拷貝這些原型創(chuàng)建新的對象,下面我們就來看具體的介紹內(nèi)容吧,希望對你的學習有所幫助2022-02-02

