Function to encrypt and decrypt in PHP 7+

Asked

Viewed 200 times

2

I own the functions below:

function enCript($string, $key) 
{
    $result = '';
    $test = "";
    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));

         $test[$char]= ord($char)+ord($keychar);
         $result.=$char;
     }
     return urlencode(base64_encode($result));
  }

function deCript($string, $key) 
{
    $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 of use:

echo enCript('201910037', '7636846602');

returns:

Warning: Illegal string offset 'd' in $test[$char]= ord($char)+ord($keychar);

Warning: Illegal string offset 'g' in $test[$char]= ord($char)+ord($keychar);

Warning: Illegal string offset 'g' in $test[$char]= ord($char)+ord($keychar);

Warning: Illegal string offset 'l' in $test[$char]= ord($char)+ord($keychar);

Warning: Illegal string offset 'g' in $test[$char]= ord($char)+ord($keychar);

Warning: Illegal string offset 'h' in $test[$char]= ord($char)+ord($keychar);

Warning: Illegal string offset 'd' in $test[$char]= ord($char)+ord($keychar);

Warning: Illegal string offset 'i' in $test[$char]= ord($char)+ord($keychar);

Warning: Illegal string offset 'm' in $test[$char]= ord($char)+ord($keychar);

ZGdnbGdoZGlt
  • and what is your doubt?

  • explain to me why I use this crypt to formulate it for you

  • Not directly related to your error, but anyway: if this is just an exercise, it’s okay to create your cryptographic algorithm. But if you’re going to use it in a real system to encrypt sensitive information, nay invent your own algorithm (read more about this here and here).

1 answer

0

You’re trying to access a string as if it were a array, with a key that is a string. String You won’t understand that. In the code, we can see the problem:

"hello"["hello"];
// PHP Warning:  Illegal string offset 'hello' in php shell code on line 1

"hello"[0];
// Sem erros.

array("hello" => "val")["hello"];
//Sem erros. Isto é *Provavelmente* o que quer.

Let’s see your mistake:

Warning: Illegal string offset 'g' in $test[$char]= Ord($char)+Ord($keychar);

The error says that you are trying to use the string 'g' as an index for a string. For example:

$a_string = "string";

// aqui está certo:
echo $a_string[0]; // s
echo $a_string[1]; // t
echo $a_string[2]; // r
// ...

// isto já é errado:
echo $a_string['g'];
// !! Warning: Illegal string offset 'g' in ...

With this, you need to review your code on this line:

$char = chr(ord($char)+ord($keychar));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.