实例
点击查看代码
def rsa_encrypt(msg):
"""
RSA加密
:param pub_key_str:公钥
:param msg:待加密信息
:return:
"""
msg = msg.encode('utf-8')
length = len(msg)
default_length = 117
# 公钥加密
public_keystr = '-----BEGIN RSA PUBLIC KEY-----\n' + get_public_key() + '\n-----END RSA PUBLIC KEY-----'
pubobj = Cipher_pkcs1_v1_5.new(RSA.importKey(public_keystr))
# 长度不用分段
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)