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

时间:2014-07-24 18:08:24

标签: python encryption pycrypto

我刚开始使用PyCrypto包for python。

我在python 3.3.2下尝试以下代码:

代码参考:AES Encryption using python

#!/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 :(得分: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方法之前将bytestring解码为常规字符串。

答案 1 :(得分:0)

另一种看待它的方法是,如果在字节字符串上调用,方法rstrip接受字节字符串作为参数,如果在常规字符串上调用,则接受常规字符串。

由于decrypt的{​​{1}}返回一个字节字符串,AES object也应定义为字节字符串:

DELIMITER