Chris Nizzardini, Salt Lake City Utah, Web Developer Specializing in LAMP+Ajax Since 2006

My Blog

Here is my awesome blog. You can find information on programming, linux, documentation, tips for code and database optimization, my thoughts and rants, and whatever else I feel like sharing. Feel free to contribute to the blog by posting comments and asking questions.
Programming

PHP Data Encryption Class Implementing RIJNDAEL 256 AES standard

I am writing a pretty awesome web application and needed a way of encrypting data. So I wrote a quick class using PHPs mcrypt functions. It uses the super secure Rijndael 256 bit American Encryption Standard (AES).

Here is the class (also available for download on phpclasses.org):

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
/**
 * Crypt :: two-way encryption class using RIJNDAEL 256 AES standard
 * @uses MCRYPT_RIJNDAEL_256
 */
class Crypt
{
	private $key,$iv_size,$iv;
 
	/**
	 * constructor
	 * @param $key (string:'DefaultKey')
	 * @return void
	 */
	function __construct($key='DefaultKey'){
		$this->iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
		$this->iv = mcrypt_create_iv($this->iv_size, MCRYPT_RAND);
		$this->key = trim($key);
	}
 
	public function encrypt($string){
		$string=trim($string);
		return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->key, $string, MCRYPT_MODE_ECB, $this->iv));
	}
 
	public function decrypt($string){
		return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256,$this->key,base64_decode($string),MCRYPT_MODE_ECB,$this->iv));
	}
}

Usage

1
2
3
4
5
6
<?php
include_once 'Crypt.class.php';
$crypt = new Crypt('My_Awes0me-Key!_');
echo $crypt->encrypt('password').'<br/>'; // returns string '5IWS0SagfDMrolmoVIzkAuYbIYkHrRyymG8DdhvNKvc='
echo $crypt->decrypt('5IWS0SagfDMrolmoVIzkAuYbIYkHrRyymG8DdhvNKvc='); // returns string 'password'
?>

Related posts:

  1. capturing and storing echo or include data into a php variable
  2. setting up ssl for apache2 on debian linux
  3. Convert a PHP Object to an Array
  4. JavaScript snippet for handling credit card readers

Leave a Reply