AES-256-CBC stands for Advanced Encryption Standard with a 256-bit key in Cipher Block Chaining mode.
AES (Advanced Encryption Standard)
- A symmetric block cipher, meaning the same key is used for both encryption and decryption.
- Widely adopted as a strong encryption standard.
- Offers different key sizes: 128, 192, and 256 bits.
256-bit key
- Refers to the key length used in the AES algorithm.
- – A 256-bit key is considered extremely secure, making it difficult to crack even with powerful computers.
CBC (Cipher Block Chaining)
- An operating mode for block ciphers like AES.
- Ensures that even if the same plaintext block appears multiple times, the ciphertext will be different.
- Achieves this by XORing the previous ciphertext block with the current plaintext block before encryption.
How it works?
- Data is divided into fixed-size blocks (usually 128 bits for AES).
- The first block is encrypted with the key.
- The encrypted block is XORed with the next plaintext block before encryption.
- This process continues for all blocks.
Let’s Understand this with function
public static function encrypt_data($data, $key)
{
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$encrypted_data = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
return base64_encode($encrypted_data . '::' . $iv);
}
public static function decrypt_data($data, $key)
{
list($encrypted_data, $iv) = explode('::', base64_decode($data), 2);
return openssl_decrypt($encrypted_data, 'aes-256-cbc', $key, 0, $iv);
}
encrypt_data Function
This function encrypts data using the AES-256-CBC encryption algorithm.
Breakdown:
- Generate an Initialization Vector (IV):
openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'))generates a random IV with the appropriate length for AES-256-CBC. The IV is essential for the security of the encryption process.
- Encrypt the data:
openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv)encrypts the provided$datausing the AES-256-CBC algorithm with the given$keyand the generated IV.
- Combine encrypted data and IV:
- Concatenates the encrypted data and the IV with a ‘::’ separator.
- Base64 encode:
- Encodes the combined data into a base64 string for easier handling and transmission.
Return value:
- The function returns the base64 encoded string containing the encrypted data and the IV.
decrypt_data Function
This function decrypts data previously encrypted using the encrypt_data function.
Breakdown:
- Decode the data:
base64_decode($data)decodes the base64 encoded string back to its original format.
- Separate encrypted data and IV:
explode('::', ...)splits the decoded data into two parts: the encrypted data and the IV, using ‘::’ as the separator.
- Decrypt the data:
openssl_decrypt($encrypted_data, 'aes-256-cbc', $key, 0, $iv)decrypts the encrypted data using the provided$keyand the extracted IV.
Return value:
- The function returns the decrypted data.