Binary vs. Character: Selecting the Optimal Data Type for Hashed Passwords
Choosing the Right Data Type for Hashed Passwords in MySQL
Data Types:
There are two main options for storing hashed passwords:
- Binary: This is the preferred choice, as it efficiently stores the raw bytes of the hash without any character encoding. Common binary types include
BINARY(n)
wheren
specifies the maximum length in bytes. - Character: This can be used if the hash is converted to a string format like Base64 or hexadecimal. However, compared to binary, it uses more space due to encoding overhead and might not be compatible with all hashing algorithms. Common character types include
CHAR(n)
andVARCHAR(n)
, wheren
is the maximum length in characters.
Hash Length:
The length of the data type depends on the chosen hashing algorithm:
- BCrypt: Generates a fixed-length hash, typically around 60 characters when encoded in Base64.
- SHA-256: Generates a 256-bit (32 bytes) hash.
Here are some examples:
- Using BCrypt and Base64 encoding: You can use
BINARY(60)
to accommodate the encoded hash. - Using SHA-256: You can use
BINARY(32)
orCHAR(64)
(for hexadecimal encoding).
Related Issues and Solutions:
- Future-proofing: While current hashing algorithms are secure, consider using a data type that can accommodate longer hash lengths in case stronger algorithms are adopted in the future.
- Storage efficiency: Choosing a data type that exactly fits the hash length can optimize storage space, but be mindful of potential future changes.
Remember:
- Always use a secure hashing algorithm like BCrypt or SHA-256.
- Store the hash along with a random salt (unique per user) for added security.
- Never store passwords in plain text.
mysql hash types