How to encrypt and decrypt data in php?

2020-08-03 03:42发布

问题:

How to encrypt and decrypt data in php?

My code so far is:-

function encrypter($plaintext)
{
    $plaintext = strtolower($plaintext);
    $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256,FLENCKEY,$plaintext,MCRYPT_MODE_ECB);    
    return trim(base64_encode($crypttext));
}

function decrypter($crypttext)
{
    $crypttext = base64_decode($crypttext);    
    $plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256,FLENCKEY,$crypttext,MCRYPT_MODE_ECB);    
    return trim($crypttext);
}

$test = "abc@gmail.com";

echo encrypter(test);

Output is

iLmUJHKPjPmA9vY0jfQ51qGpLPWC/5bTYWFDOj7Hr08=

echo decrypter(test);

Output is

��-

回答1:

In your decrypter() function, you return the wrong data.

You should return $plaintext instead of $crypttext:

function decrypter($crypttext)
{
    $crypttext = base64_decode($crypttext);    
    $plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256,FLENCKEY,$crypttext,MCRYPT_MODE_ECB);    
    //return trim($crypttext);
    return trim($plaintext);
}


回答2:

The other code samples on this page (including the question) are not secure.

To be secure:

  1. Don't use mcrypt.
  2. Use authenticated encryption.
  3. Never use ECB mode (a.k.a. MCRYPT_MODE_ECB).

See this answer for secure encryption in PHP.



回答3:

This is what I use. Super simple.

function encrypt_decrypt($action, $string) {
   $output = false;
   $key = '$b@bl2I@?%%4K*mC6r273~8l3|6@>D';
   $iv = md5(md5($key));
   if( $action == 'encrypt' ) {
       $output = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, $iv);
       $output = base64_encode($output);
   }
   else if( $action == 'decrypt' ){
       $output = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, $iv);
       $output = rtrim($output, "");
   }
   return $output;
}

You can change $key to whatever you want, or leave it. (this is not my key, btw)

encrypt_decrypt('encrypt', $str) to encrypt

encrypt_decrypt('decrypt', $str) to decrypt



回答4:

Inside the decrypter function, change the

return trim($crypttext);

to

return trim($plaintext);

But looking at your function, I am not quite sure whether it will return exactly the same string, because of the strtolower function. You can't just do a strtoupper function as the original text may not be all in capital letters.



回答5:

Warning mcrypt_encrypt has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged. Use openssl_encrypt instead.