Welcome Guest, Not a member yet? Register   Sign In
Encrypt/Decrypt Confusion - Blank Decrypts
#1

New to Encrypt/Decrypt in CI4. Having a strange issue where doing an encrypt/decrypt as a test on the view page works as expected. But if I save the encrypted data into my MySQL table (varchar 255 column), when I decrypt the data, it comes back blank. Looking for any pointers or a fresh set of eyes to point out my mistake.
On page (view) works:
PHP Code:
<?php
$orig 
'4444333322221111';
$encrypter = \Config\Services::encrypter();
$key hex2bin($_ENV['encryption.key']);
$ciphertext base64_encode($encrypter->encrypt($orig$key));

?>

<p>Original: <?= $orig?></p>
<p>Encrypted: <?= $ciphertext?></p>
<p>Decrypted: <?php echo $encrypter->decrypt(base64_decode($ciphertext), $key); ?></p> 
This produces:
Code:
Original: 4444333322221111

Encrypted: QjH3ZJIaPX7N1G+VJMACMcaWZOyIWgvKGSSpNtayyytlMt04reCNuCFB7xe2Hse5CQOYswBDWxpjXHxJoMW3jDwMcs5zWV/S

Decrypted: 4444333322221111



But if I save the data to my table, like this:
PHP Code:
$post $this->request->getPost();
 
$encrypter = \Config\Services::encrypter();
 
$key hex2bin($_ENV['encryption.key']);

$ccdata['cc_num'] = base64_encode($encrypter->encrypt(cleanCCNum($post['payment_cc']), $key));

 
$this->paymentModel->replace($ccdata); 


and try to bring it back later in my controller with:
PHP Code:
$orig $payment['cc_num'];
 
$encrypter = \Config\Services::encrypter();
 
$key hex2bin($_ENV['encryption.key']);

 echo 
'<p>Original: ' $orig '</p>';
 echo 
'<p>Decrypted: ' $encrypter->decrypt(base64_decode($orig), $key) . '</p>';
 die(); 


I get: 
Code:
Original: 2OklJexxXUZIK9uPGOHE//Bc9BIHoCc5BUD5KOva3pgCYkqyivIB+MJlbJJJSE6/5yxnf5H3h/zVhJtcCoMc8js/tq3674E4

Decrypted:


So it appears to be saving correctly, but decrypting is returning an empty string.

Any help is appreciated!
Reply
#2

Is the original string the same on insert and output? That would be my first thought, inserting can seem to be looking ok but is it also correct.
Reply
#3

(09-14-2021, 02:19 AM)superior Wrote: Is the original string the same on insert and output? That would be my first thought, inserting can seem to be looking ok but is it also correct.

Thank you. Thank you!! Sometimes it takes a fresh set of eyes to point out the obvious!  Smile

The "cleanCCNum" function wasn't returning what I thought it was returning (actually it wasn't returning anything!). Once I cleaned that up, it was all good.

Thank you again.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB