MD5算法用salt散列密码

MD5 algorithm to hash passwords with salt

为什么 getBytes[ ] 和 insert bytes[ ] 给出不同的结果?

数据库:Table定义

CREATE TABLE users (
  `username` VARCHAR(15),
  `password` VARCHAR(32),
  `salt`     VARCHAR(32)
);

每当我想创建一个新用户时,我都会生成一个随机盐(类型:bytes[]),然后将其与其他列一起存储在数据库中。

但是,当我尝试使用 rs.getBytes("Salt") 从数据库中检索盐时,我不会得到相同的结果。

我知道我可以使用 rs.getString("Salt") 检索盐,但我需要将其作为 byte[] 类型获取。

我尝试将 String 转换为 Bytes[] 但结果还是不一样..!!

代码:插入数据库

String username = "admin";
String password = request.getParameter("password"); 
byte[] salt = SaltedMD5.getSalt(); 
password = SaltedMD5.getSecurePassword(password, salt); 
stmt.executeUpdate(String.format("INSERT INTO users VALUES('%s', '%s', '%s')", username, password, salt));

输出:查询结果

byte[] DB_salt = rs.getBytes("Salt");

帮自己一个忙,改用安全算法。不仅您的密码会得到妥善保护,您也不必关心盐的生成和存储。

大多数 BCrypt 实现会将生成的盐作为结果散列的一部分,因此您只需要一个最小长度为 varchar(60).

的密码散列字段
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
String hashToStoreInDb = BCrypt.hashpw(password, BCrypt.gensalt());

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from existingHashFromDb.
Boolean isPasswordCorrect = BCrypt.checkpw(password, existingHashFromDb);