I'm creating a class which performs a simple encryption/decryption for some data, using the OpenSSL extension. These are the two functions:
private function encryptData($data)
{
$iv = openssl_random_pseudo_bytes(16);
$encrypted_data = openssl_encrypt($data, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $iv);
return base64_encode($iv . $encrypted_data);
}
private function decryptData($data)
{
$decoded_data = base64_decode($data);
$iv = mb_substr($decoded_data, 0, 16);
$encrypted_data = mb_substr($decoded_data, 16, null);
return openssl_decrypt($encrypted_data, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $iv);
}
These functions works like a charm when I use them in my app, without any warning/notice/error.
I have 2 question about the PHPUnit Test:
1) Which is the best way to unit test them? Because at the moment I'm just using a reflection class to set public the functions and test encryption and decryption in the same test function (asserting the decrypted value equals to the starting value). How can I test encryption and decryption separately, as I suppose it should be?
2) My unit test fails with this: openssl_decrypt(): IV passed is only 5 bytes long, cipher expects an IV of precisely 16 bytes, padding with \0
which is weird, I checked the size of the IV in both encrypt and decrypt functions and is always 16 (used strlen() that should returns the size in bytes).
Anybody can help? thanks!