Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

Data Type สำหรับเก็บ Hashed Password ใน MySQL

Data Type ขึ้นกับ Hash Algorithm ที่ใช้ เนื่องจาก Hash คงที่ความยาว (Fixed Length) ใช้ CHAR(N) หรือ BINARY(N/2) (ผ่าน UNHEX)

อัลกอริทึมและ Data Type ที่แนะนำ

AlgorithmHex LengthCHARBINARY (with UNHEX)
MD532CHAR(32)BINARY(16)
SHA-140CHAR(40)BINARY(20)
SHA-25664CHAR(64)BINARY(32)
SHA-512128CHAR(128)BINARY(64)
bcrypt60CHAR(60)-
Argon2~96+CHAR(128+)-

ตัวอย่าง MD5

mysql> SELECT MD5('This is a hashed password');
+----------------------------------+
| MD5('This is a hashed password') |
+----------------------------------+
| e9d4c42db40abbb4724a0047f7e91e67 |
+----------------------------------+

mysql> SELECT CHAR_LENGTH(MD5('This is a hashed password'));
+----------------------------------------------------+
| CHAR_LENGTH(MD5('This is a hashed password'))      |
+----------------------------------------------------+
| 32                                                 |
+----------------------------------------------------+

ตัวอย่าง SHA-1

mysql> SELECT SHA1('This is a hashed password');
+------------------------------------------+
| SHA1('This is a hashed password')        |
+------------------------------------------+
| 4e2e1a39dba84a0b5a91043bb0e4dbef23970837 |
+------------------------------------------+

mysql> SELECT CHAR_LENGTH(SHA1('This is a hashed password'));
+-----------------------------------------------------+
| CHAR_LENGTH(SHA1('This is a hashed password'))      |
+-----------------------------------------------------+
| 40                                                  |
+-----------------------------------------------------+

Best Practice สำหรับ Password Hashing (2024+)

  1. Argon2id (Winner PHC) - ใช้ผ่าน Library (PHP password_hash, Python passlib, Node argon2)
  2. bcrypt - มาตรฐานเดิม ยังปลอดภัย (Cost Factor 12+)
  3. PBKDF2 - ต้องการ Iterations สูง (100k+)
  4. ห้ามใช้ MD5, SHA-1, SHA-256 โดยตรง (เร็วเกินไป สำหรับ Brute Force)
สำคัญ: Hash Password ใน Application Layer (ไม่ใช่ใน MySQL) ใช้ Salt เฉพาะแต่ละ User และ Algorithm ที่ออกแบบมาสำหรับ Password (Slow Hash) เท่านั้น