Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Kiểu dữ liệu nào cho trường mật khẩu hash trong MySQL?


Phụ thuộc thuật toán hash. Hash cho kết quả độ dài cố định (hex). Dùng UNHEX() để lưu binary (giảm một nửa kích thước).

Các thuật toán phổ biến

  • MD5: 32 ký tự hex → CHAR(32) hoặc BINARY(16)
  • SHA-1: 40 ký tự hex → CHAR(40) hoặc BINARY(20)
  • SHA-256: 64 ký tự hex → CHAR(64) hoặc BINARY(32)

Ví dụ MD5

mysql> SELECT MD5('This is a hashed password');
+----------------------------------+
| MD5('This is a hashed password') |
+----------------------------------+
| e9d4c42db40abbb4724a0047f7e91e67 |
+----------------------------------+
1 row in set (0.03 sec)
mysql> SELECT CHARACTER_LENGTH(MD5('This is a hashed password'));
+----------------------------------------------------+
| CHARACTER_LENGTH(MD5('This is a hashed password')) |
+----------------------------------------------------+
| 32                                                 |
+----------------------------------------------------+
1 row in set (0.04 sec)

Ví dụ SHA-1

mysql> SELECT SHA1('This is a hashed password');
+------------------------------------------+
| SHA1('This is a hashed password')        |
+------------------------------------------+
| 4e2e1a39dba84a0b5a91043bb0e4dbef23970837 |
+------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT CHARACTER_LENGTH(SHA1('This is a hashed password'));
+-----------------------------------------------------+
| CHARACTER_LENGTH(SHA1('This is a hashed password')) |
+-----------------------------------------------------+
| 40                                                  |
+-----------------------------------------------------+
1 row in set (0.00 sec)

Khuyến nghị: Dùng BINARY(n) + UNHEX() để tiết kiệm lưu trữ và so sánh nhanh hơn.