Use BLOB or VARBINARY for Encrypted Data in MySQL?

妖精的绣舞 提交于 2020-01-03 16:49:36

问题


I'm working on a PHP application that accepts user input via a text area. It will be stored encrypted in the database (using AES_ENCRYPT).

Should I use a BLOB or VARBINARY field? Are there performance implications for either type of field?


回答1:


Both BLOB and VARBINARY are "string" data types, that store binary strings (effectively byte arrays), as opposed to the usual string types, which store character strings, with charset encoding etc.

In most respects, you can regard a BLOB column as a VARBINARY column that can be as large as you like.

BLOB differs from VARBINARY in the following ways:

  • There is no trailing-space removal for BLOB columns when values are stored or retrieved.
  • For indexes on BLOB columns, you must specify an index prefix length.
  • BLOB columns can not have DEFAULT values.

Use BLOB, because if your encrypted values happen to end in a space byte (hex 20), it would be truncated with VARBINARY, effectively corrupting your value. Also, you won't be putting an index on the encrypted value so the index issue doesn't matter, nor will you have a default value.




回答2:


I don't think Bohemian's answer is accurate. VARBINARY like BLOB is to store binary data so it is capable of storing any data including spaces.

    mysql> create table t1 (id integer auto_increment, data varbinary(100), primary key (id));
Query OK, 0 rows affected (0.09 sec)

// inserting '0', ' ', '0', ' ' - 4 characters including trailing space
mysql> insert into t1 (data) values (unhex('30203020')); 
Query OK, 1 row affected (0.02 sec)

+----+------+
| id | data |
+----+------+
|  1 | 0 0  |
+----+------+
1 row in set (0.00 sec)

mysql> select t1.*, length(data) from t1;
+----+------+--------------+
| id | data | length(data) |
+----+------+--------------+
|  1 | 0 0  |            4 |
+----+------+--------------+
1 row in set (0.00 sec)


来源:https://stackoverflow.com/questions/15980025/use-blob-or-varbinary-for-encrypted-data-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!