无法加密非英语文本

时间:2017-02-10 20:23:48

标签: python aes pycrypto

我使用此代码加密字符串。 当我加密只包含英文字母的字符串时 - 它工作正常,但当我尝试加密西里尔文本时会引发异常。

import base64
from Crypto.Cipher import AES
def encrypt(text):
    BLOCK_SIZE = 16
    PADDING = '{'
    pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
    EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
    secret = "123456789101112A"
    iv = "AAAABBBBCCCCDDDD"
    cipher = AES.new(key=secret, mode=AES.MODE_CBC, IV=iv)
    return EncodeAES(cipher, text)

print(encrypt('text')) # OK
print(encrypt('абвг')) # Exception

输出

b'ZVigw9c3zTbZOrGJKJe5QQ=='
Traceback (most recent call last):
  File "/tmp/1.py", line 14, in <module>
    print(encrypt('абвг'))
  File "/tmp/1.py", line 11, in encrypt
    return EncodeAES(cipher, text)
  File "/tmp/1.py", line 7, in <lambda>
    EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
  File "/usr/lib/python3.6/site-packages/Crypto/Cipher/blockalgo.py", line 244, in encrypt
    return self._cipher.encrypt(plaintext)
ValueError: Input strings must be a multiple of 16 in length

我在填充后使用len函数验证了输入字符串。无论输入字符串是什么,它的长度总是16的倍数。文件也用utf-8和OS编码,python 3.6.0,pycrypto == 2.6.1

0 个答案:

没有答案