I have used the Encryption class to encrypt some data, setting the key in the config file, but when I try to decrypt i receive an error message:
CodeIgniter\Encryption\Exceptions\EncryptionException
Decrypting: authentication failed.
SYSTEMPATH\Encryption\Exceptions\EncryptionException.php at line 34
I believe to be following the documentation provided correctly:
https://codeigniter.com/user_guide/libraries/encryption.html#configuration
Here is my code to encrypt:
$encrypter = \Config\Services::encrypter();
$userAccount["Email"] = $encrypter->encrypt($accountData["email"]);
Here is my code to decrypt:
$encrypter = \Config\Services::encrypter();
$result->Email = $encrypter->decrypt($result->Email);
The same error has been asked here on StackOverflow
https://stackoverflow.com/questions/62781769/decrypt-showing-error-authentication-failed
Thanks
Just a thought: are you properly handling text encoding of the encrypted string? Encrypt generates binary data and using bin2hex() and hex2bin() may be recommended.
I have changed the current code to store the data in hexadecimal, using the bin2hex function. And then when trying to decrypt the message I still receive the same issue. I convert the hexadecimal to binary using the function and then try to decrypt the message.
New code to encrypt:
$encrypter = \Config\Services::encrypter();
$userAccount["Email"] = bin2hex($encrypter->encrypt($accountData["email"]));
New code to decrypt:
$encrypter = \Config\Services::encrypter();
echo $encrypter->decrypt(hex2bin($result->Email));
If I have misunderstood something, please let me know, thanks.
Have you tried a simple example just to see that all is well in your installation?
I tried this in 4.0.3 and all is well. Running macOS 10.15.5 with PHP 7.3.19:
$encrypter = \Config\Services::encrypter();
$data = '[email protected]';
$enc = $encrypter->encrypt($data);
$encrypter = \Config\Services::encrypter();
$result = $encrypter->decrypt($enc);
if ($result === $data) {
echo "OK\n";
}
else {
echo "NOT OK!\n";
}
Thank you for getting back to me, I tested what you suggested and it worked.
I realised after this, the place where I am storing the data is too small to store all the bits. The error message threw me off.
Thanks again.
Most helpful comment
I have changed the current code to store the data in hexadecimal, using the bin2hex function. And then when trying to decrypt the message I still receive the same issue. I convert the hexadecimal to binary using the function and then try to decrypt the message.
New code to encrypt:
New code to decrypt:
If I have misunderstood something, please let me know, thanks.