PHP Two-way Encryption
Syntax
string openssl_encrypt ( string $data , string $method , string $key [, int $options = 0 [, string $iv = "" [, string $tag = "" [, string $aad = "" ]]]] )
Example
$data = "This is the secret message";
$key = "my_secret_key";
$cipher = "aes-256-cbc";
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
$encrypted_data = openssl_encrypt($data, $cipher, $key, OPENSSL_RAW_DATA, $iv);
$decrypted_data = openssl_decrypt($encrypted_data, $cipher, $key, OPENSSL_RAW_DATA, $iv);
echo "Encrypted message: " . base64_encode($encrypted_data) . "\n";
echo "Decrypted message: " . $decrypted_data . "\n";
Output
Encrypted message: OBPBkiNqjBaJgMlCJp4pbgb2tBTQHD0Mg/1UzUjkFsc=
Decrypted message: This is the secret message
Explanation
The openssl_encrypt()
function encrypts the given data using the specified cipher method, key, and initialization vector (IV). The openssl_decrypt()
function decrypts the encrypted data using the same cipher method, key, and IV.
In the example above, the data is encrypted using the AES-256 CBC cipher method with a randomly generated IV. The $encrypted_data variable contains the encrypted message in binary format. The base64_encode()
function is used to convert the binary data into a string for display purposes.
The decrypted message can be obtained by passing the encrypted data, cipher method, key, and IV to the openssl_decrypt()
function.
Use
Two-way encryption can be used to securely store and transfer sensitive information such as passwords, credit card numbers, and personal identification information.
Important Points
- The same cipher method, key, and IV must be used for encryption and decryption.
- The IV should be a random sequence of bytes and should not be reused.
- Encrypted data should be securely stored and transmitted.
Summary
The openssl_encrypt()
function is used to encrypt data using a specified cipher method, key, and initialization vector. The openssl_decrypt()
function is used to decrypt the encrypted data. Two-way encryption can be used to securely store and transmit sensitive information. It is important to use a unique IV for each encryption operation and to securely store and transmit encrypted data.