Skip to content

Instantly share code, notes, and snippets.

@mllnd
Created March 6, 2019 17:00
Show Gist options
  • Save mllnd/d539e3a431bb1e36024afdc92e0089df to your computer and use it in GitHub Desktop.
Save mllnd/d539e3a431bb1e36024afdc92e0089df to your computer and use it in GitHub Desktop.
PHP CBC (Cypher Block Chaining) Encryption
<?php
define('AES_256_CBC', 'aes-256-cbc');
$data = "The string that will be encrypted/decrypted";
$encryption_key = openssl_random_pseudo_bytes(16); // 32 bytes can also be used
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(AES_256_CBC));
$encrypted = openssl_encrypt($data, AES_256_CBC, $encryption_key, 0, $iv);
echo "Encrypted: $encrypted\n";
$encrypted = $encrypted.':'.$iv;
$parts = explode(':', $encrypted);
$decrypted = openssl_decrypt($parts[0], AES_256_CBC, $encryption_key, 0, $parts[1]);
echo "Decrypted: $decrypted\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment