問題描述
我不確定密碼散列的工作原理(稍后會實現),但現在需要創(chuàng)建數據庫架構.
I'm not sure how password hashing works (will be implementing it later), but need to create database schema now.
我正在考慮將密碼限制為 4-20 個字符,但據我所知,加密后的哈希字符串將具有不同的長度.
I'm thinking of limiting passwords to 4-20 characters, but as I understand after encrypting hash string will be of different length.
那么,如何將這些密碼存儲在數據庫中?
So, how to store these passwords in the database?
推薦答案
更新:僅使用散列函數不足以存儲密碼.您應該閱讀Gilles 在此線程上的回答以獲得更詳細的解釋.
Update: Simply using a hash function is not strong enough for storing passwords. You should read the answer from Gilles on this thread for a more detailed explanation.
對于密碼,請使用密鑰強化哈希算法,例如 Bcrypt 或 Argon2i.例如,在 PHP 中,使用 password_hash() 函數,默認使用 Bcrypt.
For passwords, use a key-strengthening hash algorithm like Bcrypt or Argon2i. For example, in PHP, use the password_hash() function, which uses Bcrypt by default.
$hash = password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
結果是類似于以下的 60 個字符的字符串(但數字會有所不同,因為它生成了唯一的鹽).
The result is a 60-character string similar to the following (but the digits will vary, because it generates a unique salt).
$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
使用 SQL 數據類型 CHAR(60)
來存儲 Bcrypt 哈希的這種編碼.請注意,此函數不會編碼為一串十六進制數字,因此我們無法輕松地將其解壓縮以存儲為二進制.
Use the SQL data type CHAR(60)
to store this encoding of a Bcrypt hash. Note this function doesn't encode as a string of hexadecimal digits, so we can't as easily unhex it to store in binary.
其他散列函數仍然有用,但不能用于存儲密碼,所以我將保留下面的原始答案,寫于 2008 年.
Other hash functions still have uses, but not for storing passwords, so I'll keep the original answer below, written in 2008.
這取決于您使用的哈希算法.無論輸入如何,散列總是產生相同長度的結果.通常將二進制哈希結果用文本表示為一系列十六進制數字.或者您可以使用 UNHEX()
函數將一串十六進制數字減半.
It depends on the hashing algorithm you use. Hashing always produces a result of the same length, regardless of the input. It is typical to represent the binary hash result in text, as a series of hexadecimal digits. Or you can use the UNHEX()
function to reduce a string of hex digits by half.
- MD5 生成 128 位哈希值.您可以使用 CHAR(32) 或 BINARY(16)
- SHA-1 生成 160 位哈希值.您可以使用 CHAR(40) 或 BINARY(20)
- SHA-224 生成 224 位哈希值.您可以使用 CHAR(56) 或 BINARY(28)
- SHA-256 生成 256 位哈希值.您可以使用 CHAR(64) 或 BINARY(32)
- SHA-384 生成 384 位哈希值.您可以使用 CHAR(96) 或 BINARY(48)
- SHA-512 生成 512 位哈希值.您可以使用 CHAR(128) 或 BINARY(64)
- BCrypt 生成依賴于實現的 448 位哈希值.您可能需要 CHAR(56),CHAR(60)、CHAR(76)、BINARY(56) 或 BINARY(60)
截至 2015 年,NIST 建議使用 SHA-256或更高,用于需要互操作性的哈希函數的任何應用程序.但是 NIST 不建議使用這些簡單的哈希函數來安全地存儲密碼.
As of 2015, NIST recommends using SHA-256 or higher for any applications of hash functions requiring interoperability. But NIST does not recommend using these simple hash functions for storing passwords securely.
較小的散列算法有其用途(例如應用程序內部,而不是用于交換),但它們是已知可破解.
Lesser hashing algorithms have their uses (like internal to an application, not for interchange), but they are known to be crackable.
這篇關于用于散列密碼字段的數據類型和長度是多少?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!