public boolean authenticate(String login, String password) { try { boolean userExist = true; if (login == null || password == null) { userExist = false; login = ""; password = ""; } AuthCredential p = AuthCredential.AUTH_CREDENTIAL; AuthCredentialRecord rs = context.selectFrom(p).where(p.LOGIN.equal(login)).fetchOne(); String digest, salt; if (rs != null) { digest = rs.getPassword(); salt = rs.getSalt(); if (digest == null || salt == null) { throw new RuntimeException("Database inconsistent Salt or Digested Password altered"); } } else { digest = "000000000000000000000000000="; salt = "00000000000="; userExist = false; } byte[] bDigest = base64ToByte(digest); byte[] bSalt = base64ToByte(salt); // Compute the new DIGEST byte[] proposedDigest = getHash(password, bSalt); boolean authenticated = Arrays.equals(proposedDigest, bDigest) && userExist; if (authenticated) { rs.setJwtToken(new BigInteger(130, new SecureRandom()).toString(32)); rs.store(); } return authenticated; } catch (IOException | NoSuchAlgorithmException e) { throw new RuntimeException("Authentication failed", e); } }
public void createLogin(String login, String password) { if (StringUtils.isBlank(login) || StringUtils.isBlank(password)) { throw new IllegalArgumentException("Supplied credentials are invalid"); } try { // Salt generation 64 bits long byte[] bSalt = new byte[8]; defaultRandom.nextBytes(bSalt); // Digest computation byte[] bDigest = getHash(password, bSalt); String sDigest = byteToBase64(bDigest); String sSalt = byteToBase64(bSalt); AuthCredentialRecord credential = context.newRecord(AuthCredential.AUTH_CREDENTIAL); credential.setLogin(login); credential.setPassword(sDigest); credential.setSalt(sSalt); credential.store(); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { throw new RuntimeException("Credential creation failed", e); } }