How to encrypt plaintext with AES-256 CBC in PHP using OpenSSL?

后端 未结 1 1789
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 00:06

I am trying to encrypt sensitive user data like personal messages in my php powered website before entering into the database. I have researched a bit on the internet and I

相关标签:
1条回答
  • 2020-12-09 00:31

    AES-256 (OpenSSL Implementation)

    You're in Luck.

    The openssl extension has some pretty easy to use methods for AES-256. The steps you need to take are basically...

    1. Generate a 256-bit encryption key (This needs storing somewhere)
      • $encryption_key = openssl_random_pseudo_bytes(32);
    2. Generate an "initialization vector" (This too needs storing for decryption but we can append it to the encrypted data)
      • $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
    3. encrypt data using openssl_encrypt()
      • openssl_encrypt($data, 'aes-256-cbc', $encryptionKey, $options, $initializationVector)
      • the $options can be set to 0 for default options or changed to OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING
    4. append the initialisation vector to the encrypted data
      • $encrypted = $encrypted . ':' . $iv;
    5. retrieve the encrypted data and the initialization vector.
      • explode(':' , $encrypted);
    6. decrypt data using openssl_decrypt()
      • openssl_decrypt($encryptedData, 'aes-256-cbc', $encryptionKey, $options, $initializationVector)

    Enabling openssl

    openssl_functions() won't be available by default, you can enable this extension in your php.ini file by uncommenting the line. ;extension=php_openssl.dll by removing the leading ;

    PHP - Fiddle.

    http://phpfiddle.org/lite/code/9epi-j5v2

    0 讨论(0)
提交回复
热议问题