Encrypt/Decrypt using PHP

Post Reply
User avatar
Shane
Captain
Captain
Posts: 226
Joined: Sun Jul 19, 2009 9:59 pm
Location: Jönköping, Sweden

Encrypt/Decrypt using PHP

Post by Shane » Fri Sep 04, 2009 3:21 am

Save this code to a file names crypto.php

Code: Select all

function ENCRYPT_DECRYPT($Str_Message) {

    $Len_Str_Message=strlen($Str_Message);
    $Str_Encrypted_Message="";
    for ($Position = 0;$Position<$Len_Str_Message;$Position++){
        // long code of the function to explain the algoritm
        //this function can be tailored by the programmer modifyng the formula
        //to calculate the key to use for every character in the string.
        $Key_To_Use = (($Len_Str_Message+$Position)+1); // (+5 or *3 or ^2)
        //after that we need a module division because can´t be greater than 255
        $Key_To_Use = (255+$Key_To_Use) % 255;
        $Byte_To_Be_Encrypted = substr($Str_Message, $Position, 1);
        $Ascii_Num_Byte_To_Encrypt = ord($Byte_To_Be_Encrypted);
        $Xored_Byte = $Ascii_Num_Byte_To_Encrypt ^ $Key_To_Use;  //xor operation
        $Encrypted_Byte = chr($Xored_Byte);
        $Str_Encrypted_Message .= $Encrypted_Byte;
       
        //short code of  the function once explained
        //$str_encrypted_message .= chr((ord(substr($str_message, $position, 1))) ^ ((255+(($len_str_message+$position)+1)) % 255));
    }
    return $Str_Encrypted_Message;
} //end function

function encrypt_url($string) {
        $key = "123abc"; //preset key to use on all encrypt and decrypts.
        $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 urlencode(base64_encode($result));
}
function decrypt_url($string) {
        $key = "123abc";
        $result = '';
        $string = base64_decode(urldecode($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;
}
 
Example usage:

Code: Select all

include "crypto.php";
//index.php?A='.encrypt_url("somedata").'&val='.encrypt_url("somedata");

echo decrypt_url($_GET['val']);

$Str_Test="testword";

echo $Str_Test."<br>";
$Str_Test2 = ENCRYPT_DECRYPT($Str_Test);
echo $Str_Test2."<br><br>";
$Str_Test3 = ENCRYPT_DECRYPT($Str_Test2);
echo "<br>".$Str_Test3."<br>";
 
Notice that same function is used to do both.
Post Reply

Return to “PHP & MySQL”