cetver
cetver

Reputation: 11829

AES 128 CBC: How to calculate correct IV?

<?php

$data = '
    -What is the answer to the Ultimate Question of Life, the Universe, and Everything ?
    -42
';
$method = 'AES-128-CBC';
$password = 'secret password';
$raw_output = $raw_input = true;

$iv_len = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($iv_len);

$encrypted = openssl_encrypt($data, $method, $password, $raw_output, $iv);
var_dump($encrypted);


echo 'Decryption with known IV: OK';
$decrypted = openssl_decrypt($encrypted, $method, $password, $raw_input, $iv);
var_dump($decrypted);

echo 'Decryption with calculated IV: Fail<br><br>';
$iv = substr($encrypted, 0, $iv_len);
echo 'Without substring';
$decrypted = openssl_decrypt($encrypted, $method, $password, $raw_input, $iv);
var_dump($decrypted);
echo 'With substring';
$encrypted = substr($encrypted, $iv_len);
$decrypted = openssl_decrypt($encrypted, $method, $password, $raw_input, $iv);
var_dump($decrypted);

enter image description here

What am I doing wrong?

Upvotes: 1

Views: 2317

Answers (1)

President James K. Polk
President James K. Polk

Reputation: 41958

It seems like you are assuming that your IV is at the beginning of the encrypted output but your are not explicitly putting it there.

Try:

$encrypted = $iv . openssl_encrypt($data, $method, $password, $raw_output, $iv);

and try decrypting with:

$iv = substr($encrypted, 0, $iv_len);
$encrypted = substr($encrypted, $iv_len);
$decrypted = openssl_decrypt($encrypted, $method, $password, $raw_input, $iv);
var_dump($decrypted);

Upvotes: 3

Related Questions