Example usage for org.springframework.security.crypto.bcrypt BCrypt checkpw

List of usage examples for org.springframework.security.crypto.bcrypt BCrypt checkpw

Introduction

In this page you can find the example usage for org.springframework.security.crypto.bcrypt BCrypt checkpw.

Prototype

public static boolean checkpw(String plaintext, String hashed) 

Source Link

Document

Check that a plaintext password matches a previously hashed one

Usage

From source file:hr.diskobolos.core.crypt.PasswordHashCalc.java

/**
 * This method can be used to verify a computed hash from a plaintext (e.g.
 * during a login request) with that of a stored hash from a database. The
 * password hash from the database must be passed as the second variable.
 * You can also verify password with the BCrypt calculator:
 * https://www.dailycred.com/article/bcrypt-calculator
 *
 * @param password_plaintext The account's plaintext password, as provided
 * during a login request/*from   ww w  .  j ava  2s  . co m*/
 * @param stored_hash The account's stored password hash, retrieved from the
 * authorization database
 * @return boolean - true if the password matches the password of the stored
 * hash, false otherwise
 */
public boolean checkPassword(String password_plaintext, String stored_hash) {
    boolean password_verified = false;

    if (null == stored_hash || !stored_hash.startsWith("$2a$")) {
        throw new java.lang.IllegalArgumentException("Invalid hash provided for comparison");
    }

    password_verified = BCrypt.checkpw(password_plaintext, stored_hash);

    return (password_verified);
}

From source file:org.biokoframework.system.services.crypto.impl.EntityEncrypterTest.java

@Test
public void simpleEncryptionSaltyTest() {
    ProdEntityEncryptionService encrypter = new ProdEntityEncryptionService();

    Login login = new LoginBuilder().loadDefaultExample().build(false);
    Login encryptedLogin = encrypter.encryptEntity(login);

    assertThat(encryptedLogin, notNullValue());
    assertThat(encryptedLogin.fields().keys(), contains(login.fields().keys().toArray(new String[0])));

    for (String aFieldName : login.fields().keys()) {
        if (!aFieldName.equals(Login.PASSWORD)) {
            assertThat(encryptedLogin.get(aFieldName), is(equalTo(login.get(aFieldName))));
        }/*from   ww w.j  av  a2s  . co  m*/
    }

    assertThat(encryptedLogin.get(Login.PASSWORD), is(not(equalTo(login.get(Login.PASSWORD)))));

    assertThat(
            BCrypt.checkpw(login.get(Login.PASSWORD).toString(), encryptedLogin.get(Login.PASSWORD).toString()),
            is(true));
    assertThat(BCrypt.checkpw("A wrong password", encryptedLogin.get(Login.PASSWORD).toString()), is(false));
}

From source file:com.autoupdater.server.utils.authentication.BCryptAuthenticationManager.java

/**
 * Authenticate user.//from w w  w  .  j a va  2s.  com
 * 
 * @param auth
 *            authentication data passed by Spring Security
 * @return result of authentication
 */
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    logger.debug("Performing authentication");

    User user = null;

    logger.debug("Searching user [" + auth.getName() + "] in DB");
    try {
        user = userService.findByUsername(auth.getName());
    } catch (Exception e) {
        logger.error("User [" + auth.getName() + "] does not exists (exception)!");
        throw new AuthenticationServiceException("Error while obtaining User data!");
    }
    if (user == null) {
        logger.error("User [" + auth.getName() + "] does not exists (null)!");
        throw new BadCredentialsException("User does not exists!");
    }

    if (!BCrypt.checkpw(auth.getCredentials().toString(), user.getHashedPassword())) {
        logger.error("Password doesn't match!");
        throw new BadCredentialsException("Password doesn't match!");
    }

    logger.debug("User details are good and ready to go");
    return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(),
            getAuthorities(user.isAdmin(), user.isPackageAdmin()));
}

From source file:io.dacopancm.jfee.managedController.EditarSocioBean.java

@PostConstruct
public void postConstruct() {
    Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext()
            .getRequestParameterMap();//from   ww  w .  j a v  a2 s. c  o  m
    if (params.containsKey("r")) {
        returnPage = params.get("r");
    } else {
        returnPage = "home";
    }
    try {
        HttpServletRequest htpr = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                .getRequest();
        if (htpr.getRequestURL().toString().contains("editarSocio")) {
            if (params.containsKey("socCi") && params.containsKey("h")) {
                String hash = UriUtils.decode(params.get("h"), "UTF-8");
                String ci = params.get("socCi");
                if (BCrypt.checkpw(ci, hash)) {
                    //TODO si es administrador no pasa nada pero
                    //si es socio probar q current socio login sea el mismo a modificar
                    selectedSocio = socioService.getSocioByCi(ci);
                }
            } else {

                User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

                selectedSocio = socioService.getSocioByCi(userDetails.getUsername());

            }
        } else {
            User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

            selectedSocio = socioService.getSocioByCi(userDetails.getUsername());
        }
    } catch (Exception ex) {
        log.error(ex.getMessage());
    }

}

From source file:org.unitedid.auth.client.factors.PasswordFactor.java

public Boolean verify(String plaintext, String hash)
        throws UnsupportedEncodingException, NoSuchAlgorithmException {
    return BCrypt.checkpw(sha256PreHash(plaintext), hash);
}

From source file:de.appsolve.padelcampus.utils.LoginUtil.java

public LoginCookie isValidLoginCookie(String uuid, String loginCookieRandomValue) {
    LoginCookie loginCookie = loginCookieDAO.findByUUID(uuid);
    if (loginCookie == null) {
        return null;
    }/*ww w. j  a  v  a2 s  .c o  m*/
    if (BCrypt.checkpw(loginCookieRandomValue, loginCookie.getLoginCookieHash())) {
        return loginCookie;
    }
    return null;
}

From source file:edu.jhuapl.openessence.security.OEPasswordEncoder.java

/**
 *
 * @param encPass/*from   www.  j ava  2  s.  c o m*/
 * @param rawPass
 * @param encryptDetails an {@link EncryptionDetails} object
 * @return The encrypted version of the password
 * @throws DataAccessException
 */
@Override
public boolean isPasswordValid(String encPass, String rawPass, Object encryptDetails)
        throws DataAccessException {
    if ((encryptDetails == null) || !(encryptDetails.getClass().equals(EncryptionDetails.class))) {
        return false;
    }
    String algorithm = ((EncryptionDetails) encryptDetails).getAlgorithm();
    boolean checkPass = false;
    if (algorithm.equals("BCrypt")) {
        checkPass = BCrypt.checkpw(rawPass, encPass);
    } else {
        checkPass = encodePassword(rawPass, encryptDetails).equals(encPass);
    }

    return checkPass;
}

From source file:io.wicket.cas.BCryptSearchModeSearchDatabaseAuthenticationHandler.java

/**
 * Check password using BCrypt algorithm.
 *
 * @param plainTextPassword Plain text password.
 * @param encryptedPassword Known encrypted.
 * @return boolean isValid?//  w  ww . ja  va2s  .  c o m
 */
private boolean isPasswordValid(String plainTextPassword, String encryptedPassword) {
    return !(plainTextPassword == null || plainTextPassword.trim().length() == 0 || encryptedPassword == null
            || encryptedPassword.trim().length() == 0) && BCrypt.checkpw(plainTextPassword, encryptedPassword);
}

From source file:org.biokoframework.system.services.crypto.impl.ProdEntityEncryptionService.java

private boolean checkField(String plainValue, String encryptedValue, String encryptionType) {
    if (ONE_WAY_HINT.equals(encryptionType)) {
        return BCrypt.checkpw(plainValue, encryptedValue);
    } else if (TWO_WAY_HINT.equals(encryptionType)) {
        return encryptedValue.equals(encryptField(plainValue, encryptionType));
        //         //   AES encryption, requires Java7
        //         String[] splitted = encryptedValue.split(":");
        //         TextEncryptor textEncryptor = Encryptors.queryableText(_password, splitted[1]);
        //         return textEncryptor.encrypt(plainValue).equals(splitted[0]);
    }/*  w w  w . j a  v a 2 s. c  o  m*/
    return false;
}

From source file:org.cloudfoundry.identity.uaa.scim.JdbcScimUserProvisioningTests.java

@Test
public void canChangePasswordWithouOldPassword() throws Exception {
    assertTrue(db.changePassword(JOE_ID, null, "newpassword"));
    String storedPassword = template.queryForObject("SELECT password from USERS where ID=?", String.class,
            JOE_ID);//  w w  w . ja va 2  s . c  om
    assertTrue(BCrypt.checkpw("newpassword", storedPassword));
}