We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How I can save encrypted data into mysql table?

I got the following error when I try to save encrypted data into mysql table, the column type is varchar(200)

$crypto = new Phalcon\Crypt();
$crypto->setKey($securekey);
$member->password = $crypto->encrypt($password);
$member->update();
Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\x87 \xD7\xD7\xD3\xAC...' for column ...

bin2hex can convert the encrypted data to hex string and save into varchar column also.



6.9k
Accepted
answer

You may need to change your varchar(200) to a varbinary(200) (or larger).



29.1k
edited Oct '14

OK, it works after I changed the column to varbinary(200).

3 more questions:

  1. $password is 6-16 characters, so do I need varbinary(200)? What is the min length for it?
  2. I need to use trim after decrypted, does it intend?
  3. I also saved hash value for $password, what is the max length for hash value?
$secure = new Phalcon\Security();
$secure->setWorkFactor(12);
$secure->hash($password);

Any help will be appreciated.

  1. Phalcon\Security() use BCrypt who always generates 60 character hashes. So, you can change VARBINARY(200) to VARBINARY(60), CHAR(60) or BINARY(60). I offered 200 with a reserve, just in case :)
  2. No.
  3. Total length for BCrypt is 59 or 60 bytes respectively.


29.1k

Thanks Max :)