Skip to content

Instantly share code, notes, and snippets.

@werring
Created December 23, 2014 10:14
Show Gist options
  • Select an option

  • Save werring/1303da7bd4880d9e898c to your computer and use it in GitHub Desktop.

Select an option

Save werring/1303da7bd4880d9e898c to your computer and use it in GitHub Desktop.
Encryption Class
<?php
/**
* @author T. Werring <[email protected]>
* @created 1-9-14 11:56
*/
/**
* Class Crypt
*
*/
class Crypt {
/**
* Singleton instance
*/
private static $instance = null;
/**
* @var String $key key as binary string
* @static
* @access private
*/
private static $key = null;
/**
* @var int $key_size length of binary key
* @static
* @access private
*/
private static $key_size = 0;
/**
* @var int $iv_size length of binary key
* @static
* @access private
*/
private static $iv_size = 0;
/**
* Crypt initializes default key and iv_size
*
* NOTE: ALWAYS create new 64 character hexadecimal string when reusing!
* See self::makeKey for idea to generate string
*/
private function __construct(){
self::$key = pack('H*', $this->makeKey("SOME_RANDOM_STRING"));
self::$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
}
/**
* createInstance
* @static
* @access private
* Singleton instantiation
*/
private static function createInstance(){
if(is_null(self::$instance)) self::$instance = new Crypt();
}
/**
* Encrypt
* Encrypt data in $string with RIJNDAEL 128 using $key or default key
*
* @param String $string the data to be encrypted
* @param String|null $key encryption key, null for default Crypt::$key
* @return String Encrypted data with base64 encoding
*/
public static function encrypt($string,$key=null){
self::createInstance();
$iv = mcrypt_create_iv(self::$iv_size, MCRYPT_RAND);
$key = self::$instance->makeKey($key);
return base64_encode($iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_CBC, $iv));
}
/**
* Decrypt
* Decrypt data in $string with RIJNDAEL 128 using $key or default Crypt::$key
* @param String $string base64 encrypted data
* @param String|null $key encryption key, null for default key
* @return String $key Decrypted data
*/
public static function decrypt($string, $key=null){
self::createInstance();
$key = self::$instance->makeKey($key);
$ciphertext_dec = base64_decode($string);
$iv_dec = substr($ciphertext_dec, 0, self::$iv_size);
$ciphertext_dec = substr($ciphertext_dec, self::$iv_size);
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,$ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec));
}
/**
* makeKey
* Creates a key usuable by the RIJNDAL 128 encryption
*
* @access public
* @return String key as binary string for encryption &you decryption
*/
private function makeKey($keyword){
if(is_null($keyword)) return self::$key;
$md5kw = md5($keyword);
$md5kw .=md5($md5kw);
return pack('H*', $md5kw);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment