Basic string encoding/decoding functions
Posted by: Scott
Functions:
These are basic string encoding/decoding functions I developed for use in flat-file databases. They offer limited security to protect sensitive data from being viewed.
Usage:
<?php encode($string,$key); ?> to encode.
<?php decode($string,$key); ?> to decode.
Code:
<?php
function encode($string,$key) {
$key = sha1($key);
$strLen = strlen($string);
$keyLen = strlen($key);
for ($i = 0; $i < $strLen; $i++) {
$ordStr = ord(substr($string,$i,1));
if ($j == $keyLen) { $j = 0; }
$ordKey = ord(substr($key,$j,1));
$j++;
$hash .= strrev(base_convert(dechex($ordStr + $ordKey),16,36));
}
return $hash;
}
function decode($string,$key) {
$key = sha1($key);
$strLen = strlen($string);
$keyLen = strlen($key);
for ($i = 0; $i < $strLen; $i+=2) {
$ordStr = hexdec(base_convert(strrev(substr($string,$i,2)),36,16));
if ($j == $keyLen) { $j = 0; }
$ordKey = ord(substr($key,$j,1));
$j++;
$hash .= chr($ordStr - $ordKey);
}
return $hash;
}
?>
Example #1:
Encode:
<?php echo encode("Please Encode Me!","This is a key"); ?>
Result:
p3e4e4241674d2r4m4i5o464a4f2p3k5c2
Decode:
<?php echo decode("p3e4e4241674d2r4m4i5o464a4f2p3k5c2","This is a key"); ?>
Result:
Please Encode Me!
Example #2:
Encode:
<?php echo encode("Please Encode Me!","A New Key"); ?>
Result:
t3t5e434q494f2m4s5j5w544b4d2m3k5i2
Decode:
<?php echo decode("t3t5e434q494f2m4s5j5w544b4d2m3k5i2","A New Key"); ?>
Result:
Please Encode Me!
Views: 27074