1

I'm trying to encrypt a message using AES-256-CBC but I get different behavior in Ruby and Python versions. It seems like Python's AES encryption does not add a suffix.

require 'base64'
require 'aescrypt'

key = "z\r}\xE6\xB5\xB0P:\x80D@+\x96S\xAB (\x87\xDD#3x\xB9\xF3\xB4\xE7*qTKz\xC1"
iv = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
data = "\xC7u\xE7\xB7W\xED\xE60\xCD\n\xA1\x11;\xD1\x02f\x1A\xB3\x88)\xCAR\xA6B*\xB7\x82\x86/&\x86F"

Base64.encode64(AESCrypt.encrypt_data(data, key, iv, "AES-256-CBC"))

=> "ldB7M0nr+FP6I9NiogtvysUFfUC2vIt6Hj7cwzEiUEal76Cpyc+x6RTiHgkq\n6j7n\n"

Whereas in Python using cryptography:

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import base64
backend = default_backend()

key = "z\r}\xE6\xB5\xB0P:\x80D@+\x96S\xAB (\x87\xDD#3x\xB9\xF3\xB4\xE7*qTKz\xC1"
iv = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
data = "\xC7u\xE7\xB7W\xED\xE60\xCD\n\xA1\x11;\xD1\x02f\x1A\xB3\x88)\xCAR\xA6B*\xB7\x82\x86/&\x86F"

cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
ct = encryptor.update(data) + encryptor.finalize()
base64.b64encode(ct)

=> 'ldB7M0nr+FP6I9NiogtvysUFfUC2vIt6Hj7cwzEiUEY='

You can see the encrypted text produced by Ruby library has extra 16 bytes. I have Java code as well which produces exact same ciphertext as Ruby version. Python code is behaving oddly. How can I change the Python code so that it produces the same ciphertext?

2
  • It looks like you're using Python 2. Is that correct? Commented Sep 15, 2018 at 10:09
  • I just remembered I wrote an answer for AES CBC using the cryptography package a few months ago. You may find it helpful. Note the PKCS7 padding. stackoverflow.com/a/50063211/4014959 Commented Sep 15, 2018 at 13:24

1 Answer 1

2

A friend pointed out the problem: the encrypt method requires padded data:

from Crypto.Util.Padding import pad
ct = encryptor.update(pad(data,16)) + encryptor.finalize()
Sign up to request clarification or add additional context in comments.

1 Comment

You should be able to accept your own answer by now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.