PHP Encryption and Decryption Class

From CoderLearner
Jump to: navigation, search

Description

Create custom class for encryption and decryption.

Class.php

<?php
class Encryption
{
	private static $key = "I@Love#2001$$$";
	public static function encrypt($string)
	{
		$key = Encryption::$key;
		$result = "";
		for ($i = 0; $i < strlen($string); $i++)
		{
			$char = substr($string, $i, 1);
			$keychar = substr($key, ($i % strlen($key)) - 1, 1);
			$char = chr(ord($char) + ord($keychar));
			$result.= $char;
		}
		return base64_encode($result);
	}
	public static function decrypt($string)
	{
		$key = Encryption::$key;
		$result = "";
		$string = base64_decode($string);
                for ($i = 0; $i < strlen($string); $i++)
		{
			$char = substr($string, $i, 1);
			$keychar = substr($key, ($i % strlen($key)) - 1, 1);
			$char = chr(ord($char) - ord($keychar));
			$result.=$char;
		}
		return $result;
	}
}
?>

Test It

<?php
include 'Class.php';

// assign password
$password = 'so$sc32dcda';

// generate encryption password
$password_encrypt = Encryption::encrypt($password);

// decryption the encrypted password
$password_decrypt = Encryption::decrypt($password_encrypt);

// display result
echo 'Password: ' . $password . "<br/>";
echo 'Encryption password: '. $password_encrypt . "<br/>";
echo 'Decryption password: '. $password_decrypt . "<br/>";

?>

Result

Password: so$sc32dcda
Encryption password: l7hkv9Kpl4eVlJE=
Decryption password: so$sc32dcda
How to connect to MySQL with this function