douwen9343 2015-02-03 03:40
浏览 195
已采纳

用于PHP的GCM身份验证加密功能

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?

  • 写回答

1条回答 默认 最新

  • dounianji7883 2015-02-03 09:19
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?