RSA分段加解密

分段加密

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()

你可能感兴趣的:(RSA分段加解密)