Encryption and Decryption

April 28th, 2008 | by admin | |

Something I struggled to find when starting out was good, non standard encryption and decryption functions. Here’s a couple for you to use/adapt as you wish.

NOTE, these make use of a PHP constant called SALT. So make sure you define this first (see start of code for SALT)

<?php
#SALT (key used in encryption)
define("SALT", "you will never guess");

#encrypt a string
function encrypt($string) {
	$result = '';
	for($i = 0; $i < strlen($string); $i++) {
		$char = substr($string, $i, 1);
		$keychar = substr(SALT, ($i % strlen(SALT))-1, 1);
		$char = chr(ord($char)+ord($keychar));
		$result.=$char;
	}
	return base64_encode($result);
}

#decrypt an encrypted string
function decrypt($string) {
	$result = '';
	$string = base64_decode($string);
	for($i = 0; $i < strlen($string); $i++) {
		$char = substr($string, $i, 1);
		$keychar = substr(SALT, ($i % strlen(SALT))-1, 1);
		$char = chr(ord($char)-ord($keychar));
		$result.=$char;
	}
	return $result;
}
?>

Post a Comment