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?
function to encrypt and decrypt strings
Moderator: General Moderators
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
If you need to be able to reverse the encryption then perhaps the mcrypt() functions?
- AKA Panama Jack
- Forum Regular
- Posts: 878
- Joined: Mon Nov 14, 2005 4:21 pm
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.
The key can be any alpha-numeric string of any length.
Here is the encoding function.
This would encode your data.
Here is the decoding function.
And decoding your data.
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.
First define your encryption key.
Code: Select all
define ("OrdKey","j0w06ej3gw29jn3h1");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);
}Code: Select all
$mydata = "How now brown cow.";
$mydata_encoded = ord_crypt_encode($mydata);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;
}Code: Select all
$mydata = ord_crypt_decode($mydata_encoded);