NerdyHearn
Home
Blog

Contact
Mailing List

Software


Blog
Twitter

NerdyHearn - Blog


<< Back To All Blogs

Simple encryption class for PHP

Tuesday, March 31st, 2009

I've been doing some PHP encryption work lately, and seeing as such wrote a class to simplify the process. Hopefully this will save some of you some reading on the numerous options with PHP's mcrypt library. That being said I would not just copy this as is and assume you have secure encryption. 99% of encryption/decryption is understanding the process, and what you are doing. Take some time and read up on encryption if you have not done so already.

Without further ado, I present to you the Cipher class.

class Cipher {
var $securekey = "";
var $iv = "";
var $iv_size = 32;

function Cipher($textkey) {
$this->securekey = hash('sha256',$textkey,TRUE);
$this->iv = mcrypt_create_iv($this->iv_size);
}
function encrypt($input) {
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->securekey, $input, MCRYPT_MODE_ECB, $this->iv));
}
function decrypt($input) {
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->securekey, base64_decode($input), MCRYPT_MODE_ECB, $this->iv));
}
}

Not very difficult. But as some sample usage:

$cipher = new Cipher('secret passphrase');

$encrypted = $cipher->encrypt("you should encrypt me");
echo $encrypted;

$decrypted = $cipher->decrypt($encrypted);
echo $decrypted;

There are a whole number of different encryption algorithms available if you were to need to change from Rijndael, but it is very well-known and time-proven so if you need a quick and easy encryption class, just copy and paste and go to town!

Encryptin' Tom Out.

Tags

PHP Encryption

Related Blogs

Netbeans and PHP: A promising future
Parsing XML in PHP with SimpleXML

Implementing AJAX with PHP and MySQL
Calling .NET WebService From PHP

Comments

Currently no comments.

Add A Comment

Name:


URL:


Email Address: (not public, used to send notifications on further comments)


Comments:



Enter the text above, except for the 1st and last character:


NerdyHearn - Latest tech news relating to C#, ASP.NET, SharePoint, PHP, general development, and more. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers