首页 > 解决方案 > Python3 PKCS7编码器

问题描述

我尝试使用 PKCS7Encoder 解密和加密 pycryptodome

我的密码器.py

# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
import base64
import json
from pkcs7 import PKCS7Encoder

class Crypter(object):
    def __init__(self):
        self.encoder=PKCS7Encoder()

    def decrypt(self,input,key):
        return self.encoder.decode(AES.new(base64.b64decode(key), AES.MODE_CBC, '\x00'*16).decrypt(base64.b64decode(input)))

    def encrypt(self,input,key):
        padded_data=self.encoder.encode(json.dumps(input))
        return base64.b64encode(AES.new(base64.b64decode(key), AES.MODE_CBC, '\x00'*16).encrypt(padded_data))

我的 pkcs7.py

import binascii
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

class PKCS7Encoder(object):
    def __init__(self, k=16):
        self.k = k

    def decode(self, text):
        '''
        Remove the PKCS#7 padding from a text string
        '''
        nl = len(text)
        val = int(binascii.hexlify(text[-1]), 16)
        if val > self.k:
            raise ValueError('Input is not padded or padding is corrupt')

        l = nl - val
        return text[:l]

    def encode(self, text):
        '''
        Pad an input string according to PKCS#7
        '''
        l = len(text)
        output = StringIO()
        val = self.k - (l % self.k)
        for _ in range(val):
            output.write('%02x' % val)
        return text + binascii.unhexlify(output.getvalue())

它总是像这样返回错误

return text + binascii.unhexlify(output.getvalue()) TypeError: can only concatenate str (not "bytes") to str

我尝试将字节更改为 str 不起作用,有什么解决方案吗?

标签: python-3.xpkcs#7

解决方案


推荐阅读