Home > Dev > Crypto > AES-256 Encryption and Decryption

AES-256 Encryption and Decryption

This code snippet demonstrates how to securely encrypt and decrypt data using AES-256-CBC.

function encrypt($plaintext, $key) {
    $iv_length = openssl_cipher_iv_length('aes-256-cbc');
    $iv = openssl_random_pseudo_bytes($iv_length);
    $ciphertext = openssl_encrypt($plaintext, 'aes-256-cbc', $key, 0, $iv);
    return base64_encode($iv . $ciphertext);
}

function decrypt($ciphertext, $key) {
    $ciphertext = base64_decode($ciphertext);
    $iv_length = openssl_cipher_iv_length('aes-256-cbc');
    $iv = substr($ciphertext, 0, $iv_length);
    $ciphertext = substr($ciphertext, $iv_length);
    return openssl_decrypt($ciphertext, 'aes-256-cbc', $key, 0, $iv);
}

// Usage example
$key = 'your-encryption-key-here'; // Must be 32 bytes for AES-256
$plaintext = 'This is a secret message';
$encrypted = encrypt($plaintext, $key);
$decrypted = decrypt($encrypted, $key);

echo "Encrypted: " . $encrypted . "\n";
echo "Decrypted: " . $decrypted . "\n";
Back