2

I searched for how to use openssl_encrypt correctly, and found several stackoverflow questions and answers. However, I'm afraid I just can't get it to work.

My current code looks like this:

$encryption_key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(32);
$encrypted = openssl_encrypt($data, 'AES-256-CTR', $encryption_key, 0, $iv);
$error = openssl_error_string();
var_dump($encrypted, $error);

The var_dump just gives me bool(false) bool(false). It doesn't work and I don't get any error.

Anyone can help me?

EDIT: I don't know what exactly the problem was, but apparently using AES-256-CTR did not work on the system. Using AES-256-CBC with above code works just fine...

Danmoreng
  • 2,367
  • 1
  • 19
  • 32

1 Answers1

0

It doesn't give an error, because you forgot to enable error reporting in PHP. If you did, you would have seen:

E_WARNING : type 2 -- openssl_encrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating -- at line 6

AES is a block cipher with a fixed block size of 128 bit or 16 byte. The nonce for CTR mode (here called IV for initialization vector) must be at most as long as the block size. For optimal security, it is a good practice to use a nonce that is 96 bit or 12 byte long. The remaining 32 bit or 4 byte can be filled with zeros:

$iv = openssl_random_pseudo_bytes(12) . "\0\0\0\0";

If you use CBC mode, then you need to use:

$iv = openssl_random_pseudo_bytes(16);
Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222