Page 1 of 1

function to encrypt and decrypt strings

Posted: Fri Dec 09, 2005 9:22 am
by greyhound
Hi Guys,

I need a php function that shows the same behavior as the mysql functions encode & decode:
to encrypt a given string using a password string and later decrypt it.

Does something like this exists in php?

Posted: Fri Dec 09, 2005 11:00 am
by Chris Corbyn
If you need to be able to reverse the encryption then perhaps the mcrypt() functions?

Posted: Fri Dec 09, 2005 2:26 pm
by AKA Panama Jack
Here is a simple but effective one that doesn't require any extra modules/libraries, like mycrypt, to be installed on the server.

First define your encryption key.

Code: Select all

define ("OrdKey","j0w06ej3gw29jn3h1");
The key can be any alpha-numeric string of any length.

Here is the encoding function.

Code: Select all

function ord_crypt_encode($data) {
	$result = '';
	for($i=0; $i<strlen($data); $i++) {
		$char = substr($data, $i, 1);
		$keychar = substr(OrdKey, ($i % strlen(OrdKey))-1, 1);
		$char = chr(ord($char)+ord($keychar));
		$result.=$char;
	}
	return bin2hex($result); 
}
This would encode your data.

Code: Select all

$mydata = "How now brown cow.";

$mydata_encoded = ord_crypt_encode($mydata);
Here is the decoding function.

Code: Select all

function ord_crypt_decode($data) {
	$result = '';
	$data =  @pack("H" . strlen($data), $data); 

	for($i=0; $i<strlen($data); $i++) {
		$char = substr($data, $i, 1);
		$keychar = substr(OrdKey, ($i % strlen(OrdKey))-1, 1);
		$char = chr(ord($char)-ord($keychar));
		$result.=$char;
	}
	return $result;
}
And decoding your data.

Code: Select all

$mydata = ord_crypt_decode($mydata_encoded);
It is not as fast as using a library like mcrypt but it does do the job quite well and will work on any server since it doesn't have any library requirements.