Advertisement
Guest User

PHP Class - OpenSSL Encryption

a guest
Jan 29th, 2015
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.32 KB | None | 0 0
  1. <?php
  2.     /* ========================================
  3.     Class for encrypting and decrypting data
  4.     using the OpenSSL and MCRYPT libraries
  5.  
  6.     Requires PHP 5.4+ and the OpenSSL and
  7.     MCRYPT libraries be installed.
  8.  
  9.     @author: rbrotherton@gmail.com
  10.     @license: Unlicensed
  11.    ======================================== */
  12.  
  13.     class OpenSSL {
  14.  
  15.         protected $cipher_mcrypt  = MCRYPT_RIJNDAEL_128;
  16.         protected $cipher_openssl = 'aes-256-cbc';
  17.  
  18.         // Constructor
  19.         public function __construct(){
  20.  
  21.         }
  22.  
  23.         // How to behave when treated like a string
  24.         public function __toString(){
  25.             return "OpenSSL/MCRYPT encryption object.";
  26.         }
  27.        
  28.         public function encrypt($data, $key){
  29.            
  30.             $vector_size = mcrypt_get_iv_size($this->cipher_mcrypt, MCRYPT_MODE_CBC);
  31.             $vector      = mcrypt_create_iv($vector_size, MCRYPT_DEV_URANDOM);
  32.             $encrypted   = openssl_encrypt($data, $this->cipher_openssl, $key, 0, $vector);
  33.  
  34.             // Pass the initialization vector along with our data string so we can decode later
  35.             return $vector . $encrypted;
  36.  
  37.         }
  38.  
  39.         public function decrypt($data, $key){
  40.  
  41.             $vector_size = mcrypt_get_iv_size($this->cipher_mcrypt, MCRYPT_MODE_CBC);
  42.             $vector      = substr($data, 0, $vector_size);
  43.             $data        = substr($data, $vector_size);
  44.             return openssl_decrypt($data,$this->cipher_openssl, $key, 0, $vector);
  45.  
  46.         }
  47.  
  48.     }
  49.  
  50.  
  51. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement