Advertisement
koki2000

Encrypt and decrypt with secret key PHP algorithm

Oct 29th, 2018
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.28 KB | None | 0 0
  1. <?php
  2.     /*
  3.      * https://bhoover.com/using-php-openssl_encrypt-openssl_decrypt-encrypt-decrypt-data/
  4.      * @param $data
  5.      * @param $key
  6.      * @return string
  7.      */
  8.  
  9.     function encrypt($data, $key)
  10.     {
  11.         //Remove the base64 encoding from our key
  12.         $encryption_key = base64_decode($key);
  13.         // Generate an initialization vector
  14.         $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
  15.         // Encrypt the data using AES 256 encryption in CBC mode using our encryption key and initialization vector.
  16.         $encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv);
  17.         // The $iv is just as important as the key for decrypting, so save it with our encrypted data using a unique separator (::)
  18.         return base64_encode($encrypted . '::' . $iv);
  19.     }
  20.     echo encrypt('string', 1234);
  21.     echo '<br />';
  22.    
  23.     function decrypt($data, $key)
  24.     {
  25.         //Remove the base64 encoding from our key
  26.         $encryption_key = base64_decode($key);
  27.         // To decrypt, split the encrypted data from our IV - our unique separator used was "::"
  28.         list($encrypted_data, $iv) = explode('::', base64_decode($data), 2);
  29.         return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);
  30.        
  31.     }
  32.     echo decrypt('NlZDN2trR1R1K3diaERNa2ROMjZ2dz09OjoRssvy+nlh9tszAHCXW3E8', 1234);
  33.    
  34.    
  35.  
  36. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement