RSA分段加解密

本文介绍了使用RSA算法进行分段加密和解密的过程。在加密部分,通过读取私钥文件,对消息进行UTF-8编码并按117个字符进行分段加密,最后将所有加密片段拼接成完整的密文。解密时,首先对密文进行base64解码,再用公钥文件解密,同样按128个字符分段处理,最后将所有解密片段拼接成原始消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分段加密

def encrypt(message):
# 获取私钥
with open(‘private.pem’) as f:
key = f.read()
try:
# 分段加密
pubobj = RSA.importKey(key)
cipher_rsa = PKCS1_OAEP.new(pubobj)
a = message.encode(‘utf-8’)
# print(type(a))
res = []
for i in range(0, len(a), 117):
# print(i)
enc_tmp = cipher_rsa.encrypt(a[i:i + 117])
res.append(enc_tmp)
print(res)
# 加密完进行拼接
cipher_text = b’’.join(res)
except Exception as e:
print(“RSA分段加密异常.”, e)
else:
# base64进行编码
return base64.b64encode(cipher_text).decode()

分段解密

def decrypt(cipher_text):
“”“RSA解密步骤:
1.对cipher_text进行base64解码:binascii.a2b_base64(cipher_text)
2.对上一步结果RSA解密:cipher.decrypt()
:param cipher_text:
“””
# base64解码
msg = base64.b64decode(cipher_text)
print(msg)
# 获取公钥
with open(‘publics.pem’) as f:
key = f.read()
try:
rsakey = RSA.importKey(key)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
b = msg.encode(‘utf-8’)
text = []
for i in range(0, len(b), 128):
text.append(cipher.decrypt(b[i:i + 100]))
# 解密完进行拼接
text = b’’.join(text)
except Exception as e:
print(e)
else:
return text.decode()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值