MD5算法用盐哈希密码

时间:2016-07-01 13:39:46

标签: java mysql hash md5 salt

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

数据库:表定义

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

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

但是,当我尝试使用rs.getBytes("Salt")从数据库中检索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");

1 个答案:

答案 0 :(得分:4)

帮自己一个忙,转而使用安全的算法。您的密码不仅可以得到正确的保护,还不必关心盐的生成和储存。

大多数BCrypt实现都会将生成的salt包含在生成的哈希中,因此您只需要一个字段用于密码哈希,最小长度为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);
相关问题