Last active
April 29, 2016 00:52
-
-
Save l4sh/071cb663882e152a03a8af004152b369 to your computer and use it in GitHub Desktop.
AES 128 CBC encription example (PHP)
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 | |
/** | |
* AES 128 CBC encription example | |
*/ | |
// Must be 64 chars long & valid hexadecimal. Store it some place safe. | |
$hex_key = "2cc4e0d365011b7d86b235c4e3dddee45ac3a76dca8536fe10d58d1d481d4b8b"; | |
$key = pack('H*', $hex_key); | |
// Initialization vector | |
$iv = openssl_random_pseudo_bytes(16); | |
// Encryption method | |
$method = 'AES-128-CBC'; | |
// Options, can be OPENSSL_RAW_DATA or OPENSSL_ZERO_PADDING. | |
$options = OPENSSL_RAW_DATA; | |
// Data to encrypt | |
$data = 'Hello, this is very sensitive data.'; | |
// Encryption process | |
$encrypted = openssl_encrypt($data, $method, $key, $options, $iv); | |
/** | |
* In order to retrieve the data later the initialization vector must be | |
* available. Since it is 16 bits long we'll concatenate it with the | |
* data, store it, and split it later before decrypting. | |
* | |
* Note that the initialization vector can be stored some place else but | |
* it **MUST** be available for decryption. | |
*/ | |
// Initialization vector along with encrypted data ready to be stored | |
$encrypted = $iv . $encrypted; | |
// Obtaining initialization vector and encrypted data | |
$s_iv = substr($encrypted, 0, 16); | |
$s_encrypted = substr($encrypted, 16); | |
$decrypted = openssl_decrypt($s_encrypted, $method, $key, $options, $s_iv); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment