Last Updated: February 25, 2016
·
515
· olsonjeremy

Get Using PHP Encryption Quick Guide

Get Using PHP Encryption Quick Guide (Ubuntu 12.04 - Apache 2.3)

  1. Download Mcrypt module:

    $ sudo apt-get install php5-mcrypt
    $ sudo service apache2 reload
  2. Edit php.ini. Uncomment these two lines:

    [mcrypt]
    mcrypt.algorithms_dir=/usr/local/lib/libmcrypt
    mcrypt.modes_dir=/usr/local/lib/libmcrypt
  3. Reload Apache.

    $ sudo service apache2 reload
  4. Use the function in your code. Here I use the function in a class:

    <?php
    
    class MyMcrypt
    {
        private $secretKey;
        private $iv;
        private $cypher = MCRYPT_RIJNDAEL_128;
        private $mode = MCRYPT_MODE_CBC;
    
        public function __construct($key)
        {
            $this->secretKey = pack('H*', md5($key));
            $this->iv  = mcrypt_create_iv(mcrypt_get_iv_size($this->cypher, $this->mode), MCRYPT_DEV_URANDOM);
        }
    
        public function getSecretKey()
        {
            return $this->secretKey;
        }
    
        public function encrypt($text)
        {
            return base64_encode(mcrypt_encrypt($this->cypher, $this->secretKey, $text, $this->mode, $this->iv));
        }
    
        public function decrypt($text)
        {
            $string = base64_decode($text);
            return mcrypt_decrypt($this->cypher, $this->secretKey, $string, $this->mode, $this->iv);
        }
    
    }
    
    $text = <<<EOL
    Bacon ipsum dolor sit amet brisket strip steak swine shank tenderloin cow kielbasa. T-bone pork belly prosciutto salami ribeye turducken drumstick ham porchetta. Short loin pancetta pastrami ribeye t-bone leberkas tongue drumstick brisket swine porchetta prosciutto shank jerky shoulder. Bacon beef chuck tongue pork loin t-bone. Frankfurter tenderloin fatback tail jerky prosciutto.
    EOL;
    
    const KEY = 'SecretKey2014IsTheYearOfTheSnake'; // 32 chars long
    
    $mcrypt = new MyMcrypt(KEY);
    $encryptedText = $mcrypt->encrypt($text);
    $unencryptedText = $mcrypt->decrypt($encryptedText);
    
    echo $encryptedText."\n";
    echo $unencryptedText."\n";