Home » Categories » PHP

Using PHP “openssl_encrypt” and “openssl_decrypt” to Encrypt and Decrypt Data

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
//$key is our base64 encoded 256bit key that we created earlier. You will probably store and define this key in a config file.
$key='bRuD5WYw5wd0rdHR9yLlM6wt2vteuiniQBqE70nAuhU=';
 
functionmy_encrypt($data,$key){
    // Remove the base64 encoding from our key
    $encryption_key=base64_decode($key);
    // Generate an initialization vector
    $iv=openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
    // Encrypt the data using AES 256 encryption in CBC mode using our encryption key and initialization vector.
    $encrypted=openssl_encrypt($data,'aes-256-cbc',$encryption_key,0,$iv);
    // The $iv is just as important as the key for decrypting, so save it with our encrypted data using a unique separator (::)
    returnbase64_encode($encrypted.'::'.$iv);
}
 
functionmy_decrypt($data,$key){
    // Remove the base64 encoding from our key
    $encryption_key=base64_decode($key);
    // To decrypt, split the encrypted data from our IV - our unique separator used was "::"
    list($encrypted_data,$iv)=explode('::',base64_decode($data),2);
    returnopenssl_decrypt($encrypted_data,'aes-256-cbc',$encryption_key,0,$iv);
}
 
//our data to be encoded
$password_plain='abc123';
echo$password_plain."<br>";
 
//our data being encrypted. This encrypted data will probably be going into a database
//since it's base64 encoded, it can go straight into a varchar or text database field without corruption worry
$password_encrypted=my_encrypt($password_plain,$key);
echo$password_encrypted."<br>";
 
//now we turn our encrypted data back to plain text
$password_decrypted=my_decrypt($password_encrypted,$key);
echo$password_decrypted."<br>";

 

Reference:

https://bhoover.com/using-php-openssl_encrypt-openssl_decrypt-encrypt-decrypt-data/

Article Rating (No Votes)
Rate this article
  • Icon PDFExport to PDF
  • Icon MS-WordExport to MS Word
 
Attachments Attachments
There are no attachments for this article.
Comments Comments
There are no comments for this article. Be the first to post a comment.
Related Articles RSS Feed
How to Install ionCube Loader in CentOS 7
Viewed 402 times since Fri, Feb 5, 2021
How do you define a PHP include as a string?
Viewed 366 times since Sun, Oct 4, 2020
"End of script output before headers" in Apache + PHP
Viewed 479 times since Sun, Feb 27, 2022
ImageTTFtextBlur $> Is there any way to make image with text shadow in PHP with GD?
Viewed 1367 times since Thu, Sep 17, 2020
PHP Warning: PHP Startup: Unable to load dynamic library ’curl’
Viewed 616 times since Thu, Feb 3, 2022
Where is path for rh-php73 in CentOS
Viewed 641 times since Fri, Feb 5, 2021
Server error: Connection reset by peer | End of script output before headers
Viewed 1354 times since Mon, Feb 28, 2022