RSA分片加密和解密

# 第一步:生成秘钥
import rsa
import base64


# 使用rsa非对称加密过程解析
class MyRsa:
    """
    1、接收者(A)生成512位公私钥对
    # a. lemon_pub为PublicKey对象, lemon_priv为PrivateKey对象
    # b. 512为秘钥的位数, 可以自定义指定, 例如: 128、256、512、1024、2048等
    # 2、发送者(B)使用接收者(A)的公钥去加密消息
    # rsa只能处理字节类型, 故字符串类型需要转化为字节类型
    """

    def __init__(self):
        self.pubkey, self.privkey = rsa.newkeys(512)

    # 加密
    def encode_string(self, string):
        string = string.encode("utf8")
        encrypt_string = rsa.encrypt(message=string, pub_key=self.pubkey)
        encrypt_string = base64.b64encode(encrypt_string)
        encrypt_string = encrypt_string.decode()
        print("加密后的串:", type(encrypt_string), encrypt_string)
        return encrypt_string

    # 解密
    def decode_string(self, encrypt_string):
        encrypt_string = encrypt_string.encode()
        encrypt_string = base64.b64decode(encrypt_string)
        encrypt_string = rsa.decrypt(crypto=encrypt_string, priv_key=self.privkey)
        encrypt_string = encrypt_string.decode(encoding="utf8")
        print("解密后:", encrypt_string)


if __name__ == '__main__':
    cl = MyRsa()
    encrypt_string = cl.encode_string(string="123456")
    cl.decode_string(encrypt_string)

# 第二步:分段式加密和解密
import rsa
import base64
# 使用rsa非对称加密过程解析
class MyRsa:
    """
    # 加密分片长度
    max_encode_len = 证书key位数/8 - 11
    # 解密分片长度
    max_decode_len = base64.b64decode(msg="无需分段加密后密文")
    # 加密的plaintext = max_len 最大长度是 证书key位数/8-11
    例如1024 bit的证书,被加密的串最长 1024/8 - 11 = 117,加密得到
    的密文长度,却恰恰是秘钥的长度
    """
    def __init__(self):
        privkey = """
        -----BEGIN RSA PRIVATE KEY-----
        MIIBPQIBAAJBAJT9epiz8kfHC/qXKlg1kcNpMPYX5E+hBM/ZMMgJ0+eaVPWuJS/9
        WPpXxqIyqSip6HIgHXadY0N/u+RC+TguHuECAwEAAQJAWzZbqcTwnNTVFpMZD2us
        U0/A88hos/9F7OFwpeat7dyuv0YxfYNUP0LBC8YMNczHw5xDwBosFCu/TgswcZoF
        4QIjALfY1OzF+MaRitfNJBxOXOwhFT7ZMnHfSxjqZFLcfLegQ80CHwDPdpF8VRRe
        z7TliSVkbuVOgJAyNNAR9RRM4m6/22UCIwChOy0I9VoGsu9D8KmhlWvSvfTG6G5g
        BUbz8+PF844A8DFlAh4zoxdjEuoXDyu/VftwnAmHGIjLdkmzroR2/oUCS+ECIwCc
        BwHTjVKowO7QcIvQ0xzmB+RziqYrumaVwy0NQGn/N92g
        -----END RSA PRIVATE KEY-----
        """
        pubkey = """
        -----BEGIN RSA PUBLIC KEY-----
   MEgCQQCU/XqYs/JHxwv6lypYNZHDaTD2F+RPoQTP2TDICdPnmlT1riUv/Vj6V8ai
        MqkoqehyIB12nWNDf7vkQvk4Lh7hAgMBAAE=
        -----END RSA PUBLIC KEY-----
        """
        # 加载秘钥对象
        self.pubkey = rsa.PublicKey.load_pkcs1(pubkey)
        self.privkey = rsa.PrivateKey.load_pkcs1(privkey)
        # 预加密计算模长
        self.max_encode_len, self.max_decode_len = self.choice_channel()
    # 预加密,获取模长
    def choice_channel(self):
        msg = "test".encode()
        models_dict = {'64': 512, '128': 1024, '512': 2048}
        # 加密,获取bytes类型的秘钥长度
        encrypt_msg = rsa.encrypt(message=msg, pub_key=self.pubkey)
        max_decode_len = len(encrypt_msg)
        print("解密模长:", max_decode_len)
        key_size = models_dict['{}'.format(max_decode_len)]
        max_encode_len = int(key_size / 8 - 11)
        print("加密模长:", max_encode_len)
        return max_encode_len, max_decode_len
    # 加密
    def encode_string(self, string):
        msg = string.encode()
        encrypt_msg = rsa.encrypt(message=msg, pub_key=self.pubkey)
        encrypt_msg = base64.b64encode(encrypt_msg)
        encrypt_msg = encrypt_msg.decode()
        print("加密后的串:", type(encrypt_msg), encrypt_msg)
        return encrypt_msg
    # 解密
    def decode_string(self, encrypt_msg):
        # 加密的逆向过程,先对字符串进行encode(),在进行base64.b64decode(encrypt_msg),在通过rsa模块
        encrypt_msg = base64.b64decode(encrypt_msg)
        decrypt_str = rsa.decrypt(crypto=encrypt_msg, priv_key=self.privkey)
        new_encrypt_str = decrypt_str.decode()
        print("解密结果:", new_encrypt_str)
        return new_encrypt_str
    # 分段加密
    def section_encode(self, msg):
        if len(msg) <= self.max_encode_len:
            print("不需要进行分段加密")
            encode_string = self.encode_string(string=msg)
            print("加密结果:", encode_string)
            return encode_string
        else:
            print("需要分段加密:")
            encode_text = []
            for i in range(0, len(msg), self.max_encode_len):
                # 需要加密的字符串进行切片
                section_text = msg[i:(i + self.max_encode_len)]
                section_text = section_text.encode()
                # 分段加密
                encode_str = rsa.encrypt(message=section_text, pub_key=self.pubkey)
                encode_text.append(encode_str)
            # 拼接加密后的bytes数据,二进制拼接起来,进行编码
            encode_bytes = b''.join(encode_text)
            encode_string = base64.b64encode(s=encode_bytes)
            encode_string = encode_string.decode()
            print("分段加密结果:", encode_string)
            return encode_string
    # 分段解密
    def section_decode(self, msg):
        decode_str = msg.encode()
        decode_str = base64.b64decode(decode_str)
        if len(decode_str) <= self.max_decode_len:
            print("不需要进行分段解密")
            decode_string = self.decode_string(encrypt_msg=msg)
            print("解密结果:", decode_string)
            return decode_string
        else:
            print("需要分段加密")
            decode_text = []
            for i in range(0, len(decode_str), self.max_decode_len):
                section_text = decode_str[i:(i + self.max_decode_len)]
                decrypt_str = rsa.decrypt(crypto=section_text, priv_key=self.privkey)
                decode_text.append(decrypt_str)
            decode_byte = b''.join(decode_text)
            decode_string = decode_byte.decode()
            print("解密结果:", decode_string)
            return decode_string
if __name__ == '__main__':
    cl = MyRsa()
    test_str = "dsdcacaadcadcadcacadcacadcacdadcacdadcacdcdcadcacadcadcacdcadcadcacadcdcdcjwfnfniwnifhybwiyvbiwviuwnviwnviwnivnwabicacbaacacacaacaacacacacaca"
    res = cl.section_encode(msg=test_str)
    cl.section_decode(msg=res)

 

posted on 2024-04-06 19:11  诚实的表达自己  阅读(92)  评论(0编辑  收藏  举报