在Python 3.3.2中使用pycrypto库时出现TypeError

2 投票
2 回答
1144 浏览
提问于 2025-04-18 14:39

我刚开始使用Python的PyCrypto库。

我在Python 3.3.2环境下尝试以下代码:

代码参考:使用Python进行AES加密

#!/usr/bin/env python

from Crypto.Cipher import AES
import base64
import os

# the block size for the cipher object; must be 16, 24, or 32 for AES
BLOCK_SIZE = 32

# the character used for padding--with a block cipher such as AES, the value
# you encrypt must be a multiple of BLOCK_SIZE in length.  This character is
# used to ensure that your value is always a multiple of BLOCK_SIZE
PADDING = '{'

# one-liner to sufficiently pad the text to be encrypted
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

# one-liners to encrypt/encode and decrypt/decode a string
# encrypt with AES, encode with base64
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)

# generate a random secret key
secret = os.urandom(BLOCK_SIZE)

# create a cipher object using the random secret
cipher = AES.new(secret)

# encode a string
encoded = EncodeAES(cipher, 'password')
print ('Encrypted string:', encoded)

# decode the encoded string
decoded = DecodeAES(cipher, encoded)
print ('Decrypted string:', decoded)

我遇到的错误是:

Traceback (most recent call last):

  File "C:/Users/Hassan Javaid/Documents/Python files/crypto_example.py", line 34, in <module>
    decoded = DecodeAES(cipher, encoded)

  File "C:/Users/Hassan Javaid/Documents/Python files/crypto_example.py", line 21, in <lambda>
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
TypeError: Type str doesn't support the buffer API

有没有人能告诉我,为什么会出现这个错误呢?

2 个回答

0

另一种理解方式是,方法 rstrip 可以接受不同类型的参数。如果你在字节字符串上调用它,它会接受一个字节字符串作为参数;如果你在普通字符串上调用它,它则会接受一个普通字符串作为参数。

因为 AES对象decrypt 方法返回的是字节字符串,所以 DELIMITER 也应该定义为字节字符串:

PADDING = b'{'
2

这是因为在 Python 3.x 中,cipher.encrypt(plain_text) 返回的是一个字节串。

而页面上给的例子使用的是 Python 2.x,在那个版本中,cipher.encrypt(plain_text) 返回的是一个普通字符串。

你可以通过使用类型函数来验证这一点:

在 Python 3.x 中:

>>> type(cipher.encrypt("ABCDEFGHIJKLMNOP"))
<class 'bytes'>

在 Python 2.x 中:

>>> type(cipher.encrypt("ABCDEFGHIJKLMNOP"))
<class 'str'>

你遇到的错误是因为你试图在字节串上使用 rstrip 方法。

使用:

DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).decode("UTF-8").rstrip(PADDING)

这样做会在使用 rstrip 方法之前,将字节串解码成普通字符串。

撰写回答