1

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!

jww
  • 97,681
  • 90
  • 411
  • 885
RavRecon
  • 43
  • 1
  • 5
  • 1
    You shouldn't test private methods directly. The fact that you need to do so might mean that there's something wrong with your design. Perhaps these methods should be public and in a separate class. – Shira Oct 16 '16 at 11:58
  • For 1: You can use the official AES test vectors, but the openssl extension should be tested for those and I don't see why you would need to repeat those tests. For 2: If you're in a multi-byte string environment, then you'll get strange results. I don't know how it should be solved correctly. – Artjom B. Oct 16 '16 at 13:20

0 Answers0