0

我已经尝试了一段时间,但找不到答案......我是这个话题的新手,所以如果它是一个基本问题,我深表歉意......

如何安全存储用户密码并让用户登录?

所以第一次用户注册时,我将对密码进行哈希+加盐并将其存储到数据库中。现在,当用户登录时,我如何检查用户是否输入了正确的密码?解密安全密码(来自数据库)然后将其与用户输入的密码进行比较没有意义吗?因为如果我可以解密它,任何人都可以...保护密码然后比较解码的密码不起作用,因为它们返回不同的值。这是我的用户注册代码:

String salt = "random232andString";
byte[] bSalt = base64ToByte(salt);
byte[] pass = null;

// pass should be what will be saved to the DB.
pass = getHash("pppppp", bSalt); //user is instance of User class.

private byte[] getHash(String password, byte[] salt) throws NoSuchAlgorithmException,     UnsupportedEncodingException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
    digest.reset();
    digest.update(salt);
    byte[] securePassword = digest.digest(password.getBytes("UTF-8"));

    return securePassword;
}

public static byte[] base64ToByte(String data){
       BASE64Decoder decoder = new BASE64Decoder();
       byte[] decoded = null;
       try {
        decoded =  decoder.decodeBuffer(data);
    } catch (IOException e) {
        e.printStackTrace();
    }
       return decoded;
}

每次我传递密码“pppppp”和上面的盐时,它都会返回不同的安全代码,比如 [B@2430f369. 那么如何将用户输入的密码与数据库中的密码匹配呢?希望这是有道理的......提前谢谢

4

1 回答 1

1

Every time I pass password "pppppp" and the above salt it returns different secure code, something like [B@2430f369

That isn't a secure code, that's how Java renders an object such as a byte[] that doesn't have a custom toString() method, when you try to print it.

[B means 'array of byte' and the @2430f369 bit is the hashCode of the object, which is different for every individual object. So calling the same function twice will give you two different byte arrays, with different [B representations, despite the contents of the arrays being the same.

If you want to look at what's inside that byte array, a traditional representation would be to hex encode it.

So how do I match user input password with that in DB?

In general you create a random salt for each new password, and you have to store that salt so that when you check the password you can generate the hash from the salt that was originally used instead of a new random one.

However. If you are creating a new account system I would strongly suggest using a strong key derivation function like bcrypt from an existing library instead of custom single-hash method. This is the new baseline for password storage these days.

于 2013-04-29T01:08:40.417 回答