0

I need to run the following on a shared web hosting account running PHP engine Version 5.4.34. (I.e. I can't install any 3rd party libraries.)

Is there a standard function to implement Galois/Counter Mode (GCM) authenticated encryption (of AES standard) on a binary string?

c00000fd
  • 20,994
  • 29
  • 177
  • 400

1 Answers1

0

If OpenSSL is not installed then, there is no other method besides looking for a plain PHP implementation on the web.

If it is installed, you can check with openssl_get_cipher_methods() whether the installed version supports GCM. Use it like this:

$strong;
$iv = openssl_random_pseudo_bytes(12, $strong);
if (!$strong) {
        exit(1);
}
$key = openssl_random_pseudo_bytes(12, $strong);
if (!$strong) {
        exit(1);
}

$data = "some string";
$ciphertext = openssl_encrypt($data, "aes-128-gcm", $key, 0, $iv);
$decrypted = openssl_decrypt($ciphertext, "aes-128-gcm", $key, 0, $iv);
var_dump($data == $decrypted);

Thanks to Scott Arciszewski for noting in the comments that this doesn't work at all for PHP < 7.1, because the authentication tag cannot be retrieved during encryption and therefore the decryption will always fail without it.

If mcrypt is installed, you may check if GCM is available there through mcrypt_list_modes, but I highly doubt it.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • Very nice, thanks. `openssl_get_cipher_methods` gives me `aes-128-gcm`, `aes-192-gcm` and `aes-256-gcm` and `mcrypt_list_modes` does not, as you surmised. I am familiar with `mcrypt` functions, but I've never come across OpenSSL in PHP. Any clues how to use it? – c00000fd Feb 03 '15 at 09:27
  • Note that the `$password` is actually the key. I updated my answer. – Artjom B. Feb 03 '15 at 09:39
  • 1
    OpenSSL's GCM doesn't work in PHP. This might get fixed in 7.1 – Scott Arciszewski Mar 04 '16 at 05:24
  • It's relevant to all versions of PHP with openssl support released thus far. The openssl extension had no way of retrieving the authentication tag, so decryption would always fail. – Scott Arciszewski Mar 04 '16 at 14:27
  • actually it states it was tested from PHP5.4 to 7.1. – My1 Nov 24 '16 at 09:08