新手遇阻:python3使用AES加密,参数can't concat str to bytes

first_param = "{rid:\"\", offset:\"0\", total:\"true\", limit:\"20\", csrf_token:\"\"}"

def get_params():
    iv = "0102030405060708"
    first_key = forth_param
    second_key = 16 * 'F'
    h_encText = AES_encrypt(first_param, first_key, iv)
    h_encText = AES_encrypt(h_encText, second_key, iv)
    return h_encText

def AES_encrypt(text, key, iv):
    pad = 16 - len(text) % 16
    text = text + pad * chr(pad)
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    encrypt_text = encryptor.encrypt(text)
    encrypt_text = base64.b64encode(encrypt_text)
    return encrypt_text

这段代码第十一行用python就会抛出can't concat str to bytes无法拼接str,试过转换bytes和转换str再合并都不行。。请教下有没有什么解决办法

阅读 7.3k
2 个回答
✓ 已被采纳新手上路,请多包涵

def AES_encrypt(text, key, iv):

pad = 16 - len(text) % 16

text = text + pad * chr(pad)
encryptor = AES.new(key, AES.MODE_CBC, iv)
encrypt_text = encryptor.encrypt(text)
encrypt_text = base64.b64encode(encrypt_text)
***encrypt_text = str(encrypt_text, encoding="utf-8")***
return encrypt_text

我刚才就遇到这个问题了,因为AES的encrypt方法的参数要求是bytes str,所以我就讲填充符转化为bytes,也就是直接在字符串前面加b’,然后就可以了。

推荐问题