python加密中文,报Input strings must be a multiple of 16 in length

python加密中文,报Input  strings must be a multiple of 16 in length

用Python做aes加密的方法:

def aes_encrypt(raw,aes_key):

#aes加密

BS = 16

pad = lambda s: (s + ((BS - len(s) % BS) * chr(BS - len(s) % BS))).encode(encoding="utf-8")

raw = pad(raw)

iv = "JFOWJFJWFKYHFWJH"

cipher = AES.new( aes_key, AES.MODE_CBC, iv )

return base64.b64encode( cipher.encrypt( raw ) )

如果我传入的待加密字符串raw是个无中文的json字符串,例如{  "seqNo" : "89420121800155111",  "userId" : "12100",  "custName" : "aaa",  "dcmttp" : "738",  "necessaryAcctNo" : "",   "agtpcu" : "1"} ,则可以加密成功.

如果传入的待加密字符串raw是包含了中文的json字符串,例如{  "seqNo" : "89420121800155111",  "userId" : "12100",  "custName" : "测试张",  "dcmttp" : "738",  "necessaryAcctNo" : "",    "agtpcu" : "1"} , 就提示报错:

File "/home/xf/zxxx.py", line 70, in aes\_encrypt  

    return base64.b64encode( cipher.encrypt( raw ) )

  File "/usr/lib/python3/dist-packages/Crypto/Cipher/blockalgo.py", line 244, in encrypt

    return self.\_cipher.encrypt(plaintext)

Error: Input strings must be a multiple of 16 in length

求教这里对中文需要怎么做处理才能不报错呢?


回答:

看提示是要求长度为16的倍数
你查下你这个加密包的函数说明
将需要加密的内容补充一下长度再加密


回答:

猜测你传进来的是unicode
unicode和string对长度的计算是不一样的,如下:

>>> len("你好")

6

>>> len(u"你好")

2

你在lambda里面先用unicode计算长度做好padding,再encode之后长度就变了。
试试改成下面这样:

def aes_encrypt(raw, aes_key):

# aes加密

BS = 16

pad = lambda s: (s + ((BS - len(s) % BS) * chr(BS - len(s) % BS)))

raw = pad(raw.encode(encoding="utf-8")) # 先encode之后,再padding

iv = "JFOWJFJWFKYHFWJH"

cipher = AES.new(aes_key, AES.MODE_CBC, iv)

return base64.b64encode(cipher.encrypt(raw))

以上是 python加密中文,报Input strings must be a multiple of 16 in length 的全部内容, 来源链接: utcz.com/a/161972.html

回到顶部