Python使用rsa模塊實現非對稱加密與解密


Python使用rsa模塊實現非對稱加密與解密

1、簡單介紹:

RSA加密算法是一種非對稱加密算法 是由已知加密密鑰推導出解密密鑰在計算上是不可行的”密碼體制。加密密鑰(即公開密鑰)PK是公開信息,而解密密鑰(即秘密密鑰)SK是需要保密的。
RSA密鑰至少為500位長,一般推薦使用1024位。RSA密鑰長度隨着保密級別提高,增加很快。
由於RSA的特性,一個1024位的密鑰只能加密117位字節數據,當數據量超過117位字節的時候,程序就會拋出異常。 ——來自大佬

2、代碼實現:

來一段大佬的代碼

import rsa


# 一、生成公鑰及私鑰, 並保存
public_key, private_key = rsa.newkeys(1024)  # 生成公鑰和私鑰
# 將生成的公鑰和私鑰進行轉換,以便存儲
pub = public_key.save_pkcs1()
pri = private_key.save_pkcs1('PEM')  # save_pkcsl()是內置方法,其默認參數是‘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)  # 轉換為原始狀態
		private_key = rsa.PrivateKey.load_pkcs1(pri)
	message = "rsa加密測試"
	info = rsa.encrypt(message.encode('utf-8'), public_key)  # 使用公鑰加密內容,內容必須是二進制
	msg = rsa.decrypt(info, private_key)  # 使用私鑰解密,獲得解密后的內容
	print(msg.decode('utf-8'))  # 使用之前記得先解碼

3、代碼升級:

現在我將上述的代碼段封裝成一個Rsa class(包含的方法有:__init__——初始化方法,key_transform_store——存儲公鑰與私鑰的方法、encry——加密方法、decry——解密方法),使用的時候,直接將下面的代碼段拎到我們需要的地方去引用:先創建一Rsa對象,然后調用里面的方法即可:

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)  # 我是真心喜歡你的。

這里會出現一個問題:由於RSA的特性,一個1024位的密鑰只能加密117位字節數據,當數據量超過117位字節的時候,程序就會拋出異常。如下測試會拋出: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)

。。。。。。

后記: 通常使用中, 會先對數據進行bas64加密, 再對加密后的內容使用rsa加密, 最后對rsa解密后的內容進行bas64解密。

以上。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM