哈希(Hash, 消息摘要)是将目标文本转换成具有相同长度的、不可逆的杂凑字符串
加密(Encrypt)是将目标文本转换成具有不同长度的、可逆的密文
图片来源:https://www.cnblogs.com/leoo2sk/archive/2010/10/01/hash-and-encrypt.html
MD5
// npm install js-md5 const md5 = require('js-md5'); console.log(md5("123456")); // e10adc3949ba59abbe56e057f20f883e
Bcrypt
- 对同一个密码,每次生成的hash不一样,但是hash中包含了salt
- 在下次校验时,从hash中取出salt,salt跟password进行hash
- 得到的结果跟保存在DB中的hash进行比对。
// npm install bcrypt const bcrypt = require('bcrypt'); const saltRounds = 10; const password = '123456'; // 生成salt const salt = bcrypt.genSaltSync(saltRounds); console.log(salt); // $2b$10$qxOMtiYuTR.sKUOpGIU9Eu // 加密 const hash = bcrypt.hashSync(password, salt); console.log(hash); // $2b$10$qxOMtiYuTR.sKUOpGIU9EugT6MjkNnrmYyjEYDD9ahIWad2esdPya // 校验 console.log(bcrypt.compareSync(password, hash)); // true); // true
加密后的格式一般为:
$2a$10$/bTVvqqlH9UiE0ZJZ7N2Me3RIgUCdgMheyTgV0B4cMCSokPa.6oCa
其中:
- $是分割符,无意义;
- 2a是bcrypt加密版本号;
- 10是cost的值;
- 而后的前22位是salt值;
- 再然后的字符串就是密码的密文了。
总结
Bcrypt生成的密文是60位的。而MD5的是32位的。
Bcrypt的破解成本更高。
参考