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
��-
Inside the decrypter function, change the
to
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.
In your
decrypter()
function, you return the wrong data.You should return
$plaintext
instead of$crypttext
:The other code samples on this page (including the question) are not secure.
To be secure:
MCRYPT_MODE_ECB
).See this answer for secure encryption in PHP.
This is what I use. Super simple.
You can change
$key
to whatever you want, or leave it. (this is not my key, btw)encrypt_decrypt('encrypt', $str)
to encryptencrypt_decrypt('decrypt', $str)
to decryptWarning mcrypt_encrypt has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged. Use openssl_encrypt instead.