python_rsa分段加密详细步骤(Plaintext is too long)

作为一个rsa菜鸟,记录下我学习过程中碰到的问题

from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as PKCS1_cipher
import base64
import random
import string

def test_01():
    random_generator = Random.new().read
    rsa = RSA.generate(1024, random_generator)
    #生成私钥
    private_key = rsa.exportKey()
    #print(private_key.decode('utf-8'))
    #print('-' * 15 + '分割线' + '-' * 15)
    with open('handong_test_privatekey.txt', 'wb') as f:
        f.write(private_key)
    #生成公钥
    public_key=rsa.public_key().exportKey()
    #print(public_key.decode('utf-8'))
    with open('handong_test_publickey.txt', 'wb') as f:
        f.write(public_key)

#加密
def rsa_encrypt(data,length=100):
    #导入公钥
    with open('D:/gaodengtest/public/handong_test_publickey.txt') as f:
        # 拼接公钥的前后缀
        #key = '-----BEGIN RSA PRIVATE KEY-----\n' + f.read() + '\n-----END RSA PRIVATE KEY-----'
        key = f.read()
        # print(key)
        # 使用 RSA 的 importKey() 方法对(从文件中读取的)公钥字符串进行处理,处理成可用的加密公钥。
        pub_key = RSA.importKey(str(key))
        # 实例化一个加密对象 cipher ,传入的参数是公钥,通过 cipher 的 encrypt() 方法对信息进行加密。
        cipher = PKCS1_cipher.new(pub_key)
    # 对传入的数据data进行编码,
    data = data.encode()
    if len(data) <= length:
        # 对编码的数据进行加密,并通过base64进行编码
        result = base64.b64encode(cipher.encrypt(data))
    else :
        rsa_text = []
        # 对编码后的数据进行切片,原因:加密长度不能过长
        for i in range(0, len(data), length):
            cont = data[i:i + length]
            # 对切片后的数据进行加密,并新增到text后面
            rsa_text.append(cipher.encrypt(cont))
        # 加密完进行拼接
        cipher_text = b''.join(rsa_text)
        # base64进行编码
        result = base64.b64encode(cipher_text)
    return result.decode()

#解密
def rsa_deencrypt(data):
    with open('D:/gaodengtest/public/handong_test_privatekey.txt') as f:
        key = f.read()
        # 使用 RSA 的 importKey() 方法对(从文件中读取的)私钥字符串进行处理,处理成可用的加密公钥。
        pub_key = RSA.importKey(str(key))
        # 实例化一个加密对象 cipher ,传入的参数是私钥,通过 cipher 的 encrypt() 方法对信息进行加密。
        cipher = PKCS1_cipher.new(pub_key)
    # 对传入的数据data进行解码
    data=base64.b64decode(data)
    #解密
    result = cipher.decrypt(data,0)
    return result.decode('utf-8')

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值