## python3 实现RSA算法分段加密解密

https://blog.csdn.net/qq_33414271/article/details/78424951

https://www.cnblogs.com/piperck/p/7257043.html

## 加密解密概念

加密和加签完全不是同样一件事情。

加密使用的是公钥对数据进行加密，而且当你使用一把1024bit的rsa公钥的时候，你一次只能加密最多117byte的数据，

256byte - 11byte = 245byte长数据。就是钥匙长度减去11byte得到的自己最大能一次加密多长的数据。如果超过了就会报错，

而加签是使用自己的私钥对需要加签的字符串进行签名。而对方需要拿着你给的公钥来验证这个数据是不是由你发出的，

## 代码实现

from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.PublicKey import RSA
import base64

'''

'''

def rsa_long_encrypt(pub_key_str, msg):
msg = msg.encode('utf-8')
length = len(msg)
default_length = 117
#公钥加密
pubobj = Cipher_pkcs1_v1_5.new(RSA.importKey(pub_key_str))
#长度不用分段
if length < default_length:
return base64.b64encode(pubobj.encrypt(msg))
#需要分段
offset = 0
res = []
while length - offset > 0:
if length - offset > default_length:
res.append(pubobj.encrypt(msg[offset:offset+default_length]))
else:
res.append(pubobj.encrypt(msg[offset:]))
offset += default_length
byte_data = b''.join(res)

return base64.b64encode(byte_data)

def rsa_long_decrypt(priv_key_str, msg):
msg = base64.b64decode(msg)
length = len(msg)
default_length = 128
#私钥解密
priobj = Cipher_pkcs1_v1_5.new(RSA.importKey(priv_key_str))
#长度不用分段
if length < default_length:
return b''.join(priobj.decrypt(msg, b'xyz'))
#需要分段
offset = 0
res = []
while length - offset > 0:
if length - offset > default_length:
res.append(priobj.decrypt(msg[offset:offset+default_length], b'xyz'))
else:
res.append(priobj.decrypt(msg[offset:], b'xyz'))
offset += default_length

return b''.join(res)

msg = '{"ApplyId":"20180504002","ChannelId":"O00420000001","LoanId":"9996401-5077812265125477811","LoanAmount":"5000.00""LoanPeriod":6,"LoanCardNo":"6225768313133272","BankId":"BANKLIST/ZHAOHANG"}'

with open('rsa-public.pem') as f:
'''读取公钥并加密'''
result = rsa_long_encrypt(key, msg)
print(result.decode('utf-8'))

with open('rsa-private.pem') as f:
'''读取私钥并解密'''
result1 = rsa_long_decrypt(key1, data)
print(result1.decode('utf-8'))

以上

posted on 2018-09-04 13:54  sammy1989  阅读(6607)  评论(2编辑  收藏  举报