哈希& Salt - 登录不同于注册

时间:2015-12-28 04:13:58

标签: javascript java spring-mvc

我试图找出为什么我的注册密码输入与登录时的摘要不同...

它们永远不会相等......我想是因为我有2个不同的base64编码器,但那不是它。

以下是注册创建用户代码:

@RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResponseEntity<String> register_Post(@RequestParam(value = "user", required = true) String username,
            @RequestParam(value = "pass", required = true) String password,
            @RequestParam(value = "expire", required = true) String time) {
        if (userService.isExistant(username))
            return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
        User user = new User();
        try {
            user.setEmailAddress(username);
            user.setEmployer(false);
            user.setActive(false);
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            byte[] bSalt = new byte[8];
            random.nextBytes(bSalt);
            String sSalt = new String(Base64.encode(bSalt), "UTF-8");
            byte[] bDigest = SecurityUtils.getHash(SecurityUtils.ITERATION_NUMBER, password, bSalt);
            String sDigest = new String(Base64.encode(bDigest), "UTF-8");
            user.setPassword(sDigest);
            user.setSalt(sSalt);
            userService.updateUser(user);
            return new ResponseEntity<String>(HttpStatus.OK);
        } catch (Exception e) {

        }
        return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
    }

以下是登录代码:

byte[] bSalt = Base64.decode(candidate.getSalt().getBytes("UTF-8"));
            byte[] prospect = Base64.decode(candidate.getPassword().getBytes("UTF-8"));
            byte[] bDigest = SecurityUtils.getHash(SecurityUtils.ITERATION_NUMBER, password, bSalt);
            if (Arrays.equals(prospect, bDigest)) 
                  return true;

这是SecurityUtils代码:

public class SecurityUtils {
     public final static int ITERATION_NUMBER = 1000;
     public static byte[] getHash(int iterationNb, String password, byte[] salt) throws NoSuchAlgorithmException, UnsupportedEncodingException {
           MessageDigest digest = MessageDigest.getInstance("SHA-1");
           digest.reset();
           digest.update(salt);
           byte[] input = digest.digest(password.getBytes("UTF-8"));
           for (int i = 0; i < iterationNb; i++) {
               digest.reset();
               input = digest.digest(input);
           }
           return input;
       }

}

使用Spring Security base64编码器。

要点: 登录和注册哈希和盐析过程看起来都是一样的,但在登录页面中进行测试则不相同。

1 个答案:

答案 0 :(得分:0)

我发现了问题......

密码未正确发送到后端......