Tuesday 3 September 2013

Encryption & Decryption class for PHP projects

In this Post Iam explaining about encryption & decryption class which can be used in php projects. In most of projects php developers will use only built in encryption techniques like base64_encode,sha1,md5.etc.
But in the class which iam providing uses most  encryption algorithms to generate code & also uses most Decryption algorithms to decrypt the code...

Here is the code:-

Copy the code and create new file named Crypt.php and save it in your library folder.

<?php

class Crypt {

var $keys;
function crypt_key($ckey){
$this->keys = array();
$c_key = base64_encode(sha1(md5($ckey)));
$c_key = substr($c_key, 0, round(ord($ckey{0})/5));
$c2_key = base64_encode(md5(sha1($ckey)));
$last = strlen($ckey) - 1;
$c2_key = substr($c2_key, 1, round(ord($ckey{$last})/7));
$c3_key = base64_encode(sha1(md5($c_key).md5($c2_key)));
$mid = round($last/2);
$c3_key = substr($c3_key, 1, round(ord($ckey{$mid})/9));
$c_key = $c_key.$c2_key.$c3_key;
$c_key = base64_encode($c_key);
for($i = 0; $i < strlen($c_key); $i++){
$this->keys[] = $c_key[$i];
}
}
function encrypt($string){
$string = base64_encode($string);
$keys = $this->keys;
for($i = 0; $i < strlen($string); $i++){
$id = $i % count($keys);
$ord = ord($string{$i});
$ord = $ord OR ord($keys[$id]);
$id++;
$ord = $ord AND ord($keys[$id]);
$id++;
$ord = $ord XOR ord($keys[$id]);
$id++;
$ord = $ord + ord($keys[$id]);
$string{$i} = chr($ord);
}
return base64_encode($string);
}
function decrypt($string){
$string = base64_decode($string);
$keys = $this->keys;
for($i = 0; $i < strlen($string); $i++){
$id = $i % count($keys);
$ord = ord($string{$i});
$ord = $ord XOR ord($keys[$id]);
$id++;
$ord = $ord AND ord($keys[$id]);
$id++;
$ord = $ord OR ord($keys[$id]);
$id++;
$ord = $ord - ord($keys[$id]);
$string{$i} = chr($ord);
}
return base64_decode($string);
}
}

?>

For decrypting the code we need a pass key also.
So if you want to use it you have to insert a demo login credintials like:-
Password: n6S+5LmuiXY=
Passkey: 6138880

So after login check the databse corresponding to this username. Fetch the passkey for corresponding data row.
Pass this passkey to the Crypt_key() function.. After that it will call encrypt function, so it will encrypt the corresponding string using that passkey...

eg:  $query = "SELECT * FROM `cms_auth` WHERE `username`='".$username)."' ";
$rec = $this->fetchAll($query);
                 $this->passKey = $rec[0]["pass_key"];
$crypt = new Crypt();
$crypt->crypt_key($this->passKey);
$password = $crypt->encrypt($this->password);

No comments:

Post a Comment