美文网首页
RSA分段加密

RSA分段加密

作者: tonyzmy | 来源:发表于2021-08-29 19:28 被阅读0次
    #coding:utf-8
    from Crypto import Random
    from Crypto.PublicKey import RSA
    
    RSA_LENGTH = 2048
    ENCRY_MAX_LENGTH = RSA_LENGTH/8 -11
    DECRY_LENGTH = RSA_LENGTH/8
    
    # 生成秘钥对实例对象:1024是秘钥的长度
    rsa = RSA.generate(RSA_LENGTH)
    
    # 获取公钥,保存到文件
    private_pem = rsa.exportKey()
    with open('private.pem', 'wb') as f:
        f.write(private_pem)
    
    # 获取私钥保存到文件
    public_pem = rsa.publickey().exportKey()
    with open('public.pem', 'wb') as f:
        f.write(public_pem)
    
    import base64
    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_v1_5
    
    
    
    def encry(msg):
        """
        公钥加密
        :param msg: 要加密内容
        :return:  加密之后的密文
        """
        # 获取公钥
        key = open('public.pem').read()
        publickey = RSA.importKey(key)
        # 分段加密
        pk = PKCS1_v1_5.new(publickey)
        encrypt_text = []
        msg = base64.b64encode(msg)
        for i in range(0,len(msg),ENCRY_MAX_LENGTH):
            cont = msg[i:i+ENCRY_MAX_LENGTH]
            encrypt_text.append(pk.encrypt(cont))
        # 加密完进行拼接
        cipher_text = ''.join(encrypt_text)
        # base64进行编码
        result = base64.b64encode(cipher_text)
        return result.decode()
    
    
    def decrypt(msg):
        """
        私钥进行解密
        :param msg: 密文:字符串类型
        :return:  解密之后的内容
        """
        # base64解码
        msg = base64.b64decode(msg)
        # 获取私钥
        privatekey = open('private.pem').read()
        rsakey = RSA.importKey(privatekey)
        cipher = PKCS1_v1_5.new(rsakey)
        # 进行解密
        text = []
        for i in range(0,len(msg),DECRY_LENGTH):
            cont = msg[i:i+DECRY_LENGTH]
            text.append(cipher.decrypt(cont,1))
        text = ''.join(text)
        return base64.b64decode(text)
    
    msg = "你好"*199
    enc = encry(msg)
    print enc
    dec = decrypt(enc)
    print dec
    

    相关文章

      网友评论

          本文标题:RSA分段加密

          本文链接:https://www.haomeiwen.com/subject/onrgiltx.html