将MD5存储在数据库中时BINARY(16)和CHAR(32)之间的差异

时间:2013-09-28 17:30:50

标签: mysql sql binary md5

根据What data type to use for hashed password field and what length?等各种建议,我可以将md5存储为CHAR(32)或BINARY(16)。但是当我使用BINARY(16)这样做时,存储的值与CHAR(32)存储结果的前16个字符以及SELECT MD5()结果的前16个字符相同。后16个字符的重要性是什么,它们是否缺少二进制列,导致数据丢失?

CREATE  TABLE test (id INT NOT NULL AUTO_INCREMENT, value VARCHAR(6), md5_char CHAR(32) NOT NULL, md5_binary BINARY(16) NOT NULL, PRIMARY KEY (id)) ENGINE = InnoDB;
INSERT INTO test(value,md5_char,md5_binary) VALUES("one!",md5("one!"),md5("one!"));
INSERT INTO test(value,md5_char,md5_binary) VALUES("two%",md5("two%"),md5("two%"));
INSERT INTO test(value,md5_char,md5_binary) VALUES("three~",md5("three~"),md5("three~"));
SELECT value,md5(value),md5_char,md5_binary FROM test;
DROP TABLE test;

+--------+----------------------------------+----------------------------------+------------------+
| value  | md5(value)                       | md5_char                         | md5_binary       |
+--------+----------------------------------+----------------------------------+------------------+
| one!   | 633c8403325f1cf963809e6eb224d77e | 633c8403325f1cf963809e6eb224d77e | 633c8403325f1cf9 |
| two%   | 48bbec047b4451a2018e0f652807b7d0 | 48bbec047b4451a2018e0f652807b7d0 | 48bbec047b4451a2 |
| three~ | fee453bb4eb68dcdfee07575e75c8cc5 | fee453bb4eb68dcdfee07575e75c8cc5 | fee453bb4eb68dcd |
+--------+----------------------------------+----------------------------------+------------------+

1 个答案:

答案 0 :(得分:7)

目前,在使用BINARY(16)时,您正在丢失一半的校验和。在BINARY(16)中存储MD5校验和时,应将其存储为二进制数据,不是以十六进制编码。那就是:

INSERT INTO test (md5_binary) VALUES(UNHEX(md5("one!")));

如果你想将它与另一个校验和进行眼球比较,你可以使用十六进制函数将其再次编码为十六进制:

SELECT HEX(md5_binary) FROM test;

使用BINARY存储校验和而不是十六进制文本的好处是需要一半的存储空间。