Last active
September 22, 2020 10:45
-
-
Save bijancot/49405f633b5a4fb6620609f83ea0552e to your computer and use it in GitHub Desktop.
encryption and decryption using openssl, with AES_256_CBC algorithm and hexadecimal data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//shoutout to turret-io (https://gist.github.com/turret-io/957e82d44fd6f4493533) | |
// just change the data type to hexadecimal | |
// DEFINE our cipher | |
define('AES_256_CBC', 'aes-256-cbc'); | |
// Generate a 256-bit encryption key | |
// This should be stored somewhere instead of recreating it each time | |
$encryption_key = 'your_encryption_key'; | |
// Generate an initialization vector | |
// This *MUST* be available for decryption as well | |
$iv = openssl_random_pseudo_bytes(16); | |
// Create some data to encrypt | |
$data = "data_to_encrypt"; | |
echo "Before encryption: $data\n"; | |
$encrypted = openssl_encrypt($data, AES_256_CBC, $encryption_key,OPENSSL_RAW_DATA, $iv); | |
//change data from binary string to hexadecimal | |
$encrypted = bin2hex($iv) . '/' . bin2hex($encrypted); | |
echo "Encrypted: $encrypted\n"; | |
// If we lose the $iv variable, we can't decrypt this, so: | |
// - $encrypted is already base64-encoded from openssl_encrypt | |
// - Append a separator that we know won't exist in base64, ":" | |
// - And then append a base64-encoded $iv | |
// To decrypt, separate the encrypted data from the initialization vector ($iv). | |
$parts = explode('/', $encrypted); | |
// $parts[0] = encrypted data | |
// $parts[1] = base-64 encoded initialization vector | |
// Don't forget to base64-decode the $iv before feeding it back to | |
//openssl_decrypt | |
$decrypted = openssl_decrypt(hex2bin($parts[1]), AES_256_CBC, $encryption_key, OPENSSL_RAW_DATA, hex2bin($parts[0])); | |
echo "Decrypted: $decrypted\n"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment