4

When using the openssl_encrypt() function in PHP to encrypt a string with AES-256-CBC as the encryption method:

$encrypted = openssl_encrypt($data, "AES-256-CBC", $key, 0, $iv);

I tried different string lengths for $data, and the resulting length of $encrypted will increase when $data reaches a multiple of 16 bytes. But it seems the growth is not steady. Is there a general formula that relates the length of $data and $encrypted?

LaBird
  • 299
  • 3
  • 13
  • This already has been answered: http://stackoverflow.com/questions/3283787/size-of-data-after-aes-encryption – Marco de Abreu Mar 07 '14 at 11:01
  • 1
    But when I tried, the result does not conform to the formula in the answer on the above link. For instance, when `data` is 0-15 bytes, 16-31 bytes, 32-47 bytes and 48-63 bytes respectively, the length of `encrypted` is 32, 60, 88 and 120 bytes respectively. – LaBird Mar 07 '14 at 11:24

1 Answers1

2

Let me quote from https://stackoverflow.com/a/3717552/2393787

With CBC mode, the input data must have a length multiple of the block length, so it is customary to add PKCS#5 padding: if the block length is n, then at least 1 byte is added, at most n, such that the total size is a multiple of n, and the last added bytes (possibly all of them) have numerical value k where k is the number of added bytes. Upon decryption, it suffices to look at the last decrypted byte to recover k and thus know how many padding bytes must be ultimately removed.

Hence, with CBC mode and AES, assuming PKCS#5 padding, if the input data has length d then the encrypted length is (d + 16) & ~15. I am using C-like notation here; in plain words, the length is between d+1 and d+16, and multiple of 16.

This states, that the length of your encrypted data can't be predicted with CBC. You should consired moving to another mode.

Community
  • 1
  • 1
Marco de Abreu
  • 663
  • 5
  • 17