Looking to Build/Redesign a Website or Blog ?

To speak to Rakshit, call +91 968 704 2303

PHP functions for Encrypt Decrypt a string

Hello Friends,

Here i am sharing php functions for encrypt decrypt a string. I came across two different ways of encrypt decrypt php functions for string. In first one, there are two functions for encrypt and decrypt string. One is for encrypt the string and other is for decrypt the encrypted string. In second one, there is only one encrypt decrypt function which works for both encryption and decryption of string in php.

// First Way – Only one function for encryption and decryption
<?php
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;
}
?>

// Second Way – PHP functions for encryption and decryption

<?php
// encript code
function encrypt($string, $key)
{
$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 base64_encode($result);
}

function decrypt($string, $key)
{
$result = ”;
$string = base64_decode($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;
}
?>

Thats it. Let me know if you find any problem.

Thank You!

Share:

1 Comment

Leave a Reply

Your email address will not be published.