Search code examples
pythonencryptionpycrypto

TypeError while using pycrypto library in python 3.3.2


I have just started using PyCrypto package for python.

I am trying out the following code under python 3.3.2:

Code Reference : 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)

The error that I run into is :

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

Any pointers to why I am getting the same ?


Solution

  • This is because cipher.encrypt(plain_text) in python 3.x returns a byte string.

    The example given in the page uses python 2.x in which case cipher.encrypt(plain_text) returned a regular string.

    You can verify the same by using the type function:

    In python 3.x:

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

    In python 2.x

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

    The error you are getting is because you are trying to use the rstrip method on a byte string.

    Use:

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

    This will decode the bytestring to regular string before using the rstrip method on it.