Java Code Examples for org.springframework.security.crypto.bcrypt.BCrypt

The following examples show how to use org.springframework.security.crypto.bcrypt.BCrypt. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
    if (encodedPassword == null || encodedPassword.length() == 0) {
        log.warn("Empty encoded password");
        return false;
    }
    if (BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
        // 匹配不到先加密再匹配
        return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
    } else {
        String ep = this.encode(encodedPassword);
        if (BCRYPT_PATTERN.matcher(this.encode(ep)).matches()) {
            return BCrypt.checkpw(rawPassword.toString(), ep);
        }
        log.warn("Encoded password does not look like BCrypt");
        return false;
    }

}
 
Example 2
Source Project: atlas   Source File: UserDao.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean checkPasswordBCrypt(String password, String encryptedPwd) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("checkPasswordBCrypt()");
    }

    boolean ret = false;

    try {
        ret = BCrypt.checkpw(password, encryptedPwd);
    } catch (Throwable excp) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("checkPasswordBCrypt(): failed", excp);
        }
    }

    return ret;
}
 
Example 3
Source Project: NFVO   Source File: CustomUserDetailsService.java    License: Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
  log.debug("Creating initial Users...");

  User admin = userRepository.findFirstByUsername("admin");
  if (!userExists("admin")) {
    User ob_admin = new User();
    ob_admin.setUsername("admin");
    ob_admin.setEnabled(true);
    ob_admin.setPassword(BCrypt.hashpw(adminPwd, BCrypt.gensalt(12)));
    Set<Role> roles = new HashSet<>();
    Role role = new Role();
    role.setRole(RoleEnum.ADMIN);
    role.setProject("*");
    roles.add(role);
    ob_admin.setRoles(roles);
    createUser(ob_admin);
  } else {
    log.debug("Admin user exists already.");
  }

  log.debug("Users in the DB: ");
  for (User user : userRepository.findAll()) {
    log.debug("" + user);
  }
}
 
Example 4
Source Project: NFVO   Source File: UserManagement.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public User add(User user) throws PasswordWeakException, BadRequestException {
  log.debug("Adding new user: " + user);

  if (customUserDetailsService.userExists(user.getUsername())) {
    throw new BadRequestException("Username exists already");
  }

  checkIntegrity(user);

  if (checkStrength) {
    Utils.checkPasswordIntegrity(user.getPassword());
  }

  user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt(12)));
  customUserDetailsService.createUser(user);
  return user;
}
 
Example 5
Source Project: ReCiter   Source File: ApplicationUserServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean authenticateUser(ApplicationUser appUser) {
	if(appUser.getId() != null
			&& !appUser.getId().isEmpty()
			&& appUser.getPassword() != null
			&& !appUser.getPassword().isEmpty()) {
		ApplicationUser validUser = applicationUserRepository.findById(appUser.getId().trim()).orElseGet(null);
		if(validUser == null) {
			return false;
		}
		if(validUser != null) {
			if(BCrypt.checkpw(appUser.getPassword(), validUser.getPassword())) {
				return true;
			}
		}
	}
	return false;
}
 
Example 6
Source Project: syncope   Source File: Encryptor.java    License: Apache License 2.0 6 votes vote down vote up
public String encode(final String value, final CipherAlgorithm cipherAlgorithm)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException {

    String encoded = null;

    if (value != null) {
        if (cipherAlgorithm == null || cipherAlgorithm == CipherAlgorithm.AES) {
            Cipher cipher = Cipher.getInstance(CipherAlgorithm.AES.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);

            encoded = Base64.getEncoder().encodeToString(cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)));
        } else if (cipherAlgorithm == CipherAlgorithm.BCRYPT) {
            encoded = BCrypt.hashpw(value, BCrypt.gensalt());
        } else {
            encoded = getDigester(cipherAlgorithm).digest(value);
        }
    }

    return encoded;
}
 
Example 7
Source Project: syncope   Source File: Encryptor.java    License: Apache License 2.0 6 votes vote down vote up
public boolean verify(final String value, final CipherAlgorithm cipherAlgorithm, final String encoded) {
    boolean verified = false;

    try {
        if (value != null) {
            if (cipherAlgorithm == null || cipherAlgorithm == CipherAlgorithm.AES) {
                verified = encode(value, cipherAlgorithm).equals(encoded);
            } else if (cipherAlgorithm == CipherAlgorithm.BCRYPT) {
                verified = BCrypt.checkpw(value, encoded);
            } else {
                verified = getDigester(cipherAlgorithm).matches(value, encoded);
            }
        }
    } catch (Exception e) {
        LOG.error("Could not verify encoded value", e);
    }

    return verified;
}
 
Example 8
Source Project: besu   Source File: TomlAuth.java    License: Apache License 2.0 5 votes vote down vote up
private void checkPasswordHash(
    final String password,
    final String passwordHash,
    final Handler<AsyncResult<Void>> resultHandler) {
  boolean passwordMatches = BCrypt.checkpw(password, passwordHash);
  if (passwordMatches) {
    resultHandler.handle(Future.succeededFuture());
  } else {
    resultHandler.handle(Future.failedFuture("Invalid password"));
  }
}
 
Example 9
Source Project: webFluxTemplate   Source File: CustomPasswordEncoder.java    License: MIT License 5 votes vote down vote up
@Override
public String encode(CharSequence rawPassword) {
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[20];
    random.nextBytes(bytes);

    String hashed = BCrypt.hashpw(rawPassword.toString(), BCrypt.gensalt(14, random));
    return hashed;
}
 
Example 10
@Override
public String encode(CharSequence rawPassword) {
    String salt;
    if (strength > 0) {
        if (random != null) {
            salt = BCrypt.gensalt(strength, random);
        } else {
            salt = BCrypt.gensalt(strength);
        }
    } else {
        salt = BCrypt.gensalt();
    }
    return BCrypt.hashpw(rawPassword.toString(), salt);
}
 
Example 11
Source Project: atlas   Source File: UserDao.java    License: Apache License 2.0 5 votes vote down vote up
public static String encrypt(String password) {
    String ret = null;

    try {
        ret = BCrypt.hashpw(password, BCrypt.gensalt());
    } catch (Throwable excp) {
        LOG.warn("UserDao.encrypt(): failed", excp);
    }

    return ret;
}
 
Example 12
/**
 * Register an user and initialises its controlled unit
 * @param username username
 * @param password plain password
 * @throws RegistrationException is username/password length is invalid
 */
public void registerUser(String username, String password) throws RegistrationException {

    if (username.length() < 5 || username.length() > 20) {
        throw new RegistrationException("Username must be 5-20 characters");
    }
    if (password.length() < 8 || password.length() > 96) {
        throw new RegistrationException("Password must be 8-96 characters");
    }

    //Check if exists
    Document where = new Document();
    where.put("_id", username);

    if (userCollection.find(where).first() != null) {
        throw new RegistrationException("Username is already in use");
    }

    try {
        User user = GameServer.INSTANCE.getGameUniverse().getOrCreateUser(username, true);
        user.setUsername(username);

        String salt = BCrypt.gensalt();
        String hashedPassword = BCrypt.hashpw(password, salt);
        user.setPassword(hashedPassword);

        Document dbUser = user.mongoSerialise();

        userCollection.insertOne(dbUser);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RegistrationException("An exception occurred while trying to create user: " + e.getMessage());
    }
}
 
Example 13
/**
 * Validate a username/password combo
 * @param username username
 * @param password plain password
 * @return true if combo is valid
 */
public boolean validateUser(String username, String password) {

    Document where = new Document();
    where.put("_id", username);

    Document user = userCollection.find(where).first();
    return user != null && BCrypt.checkpw(password, (String) user.get("password"));
}
 
Example 14
/**
 * Change the password of an user and immediately save it
 * @param username Username
 * @param newPassword New plain password
 * @throws RegistrationException When password length is invalid
 */
public void changePassword(String username, String newPassword) throws RegistrationException {

    if (newPassword.length() < 8 || newPassword.length() > 96) {
        throw new RegistrationException("Password must be 8-96 characters");
    }

    User user = GameServer.INSTANCE.getGameUniverse().getUser(username);

    String salt = BCrypt.gensalt();
    String hashedPassword = BCrypt.hashpw(newPassword, salt);
    user.setPassword(hashedPassword);

    userCollection.replaceOne(new Document("_id", username), user.mongoSerialise()); //Save new password immediately
}
 
Example 15
Source Project: vics   Source File: UserBuilder.java    License: MIT License 5 votes vote down vote up
public UserBuilder withDefaults() {
    return withFirstName("Jane")
            .withLastName("Doe")
            .withWards(newHashSet())
            .withConstituencies(newHashSet())
            .withPasswordHash(BCrypt.hashpw("password", BCrypt.gensalt()))
            .withRole(Role.USER)
            .withUsername("[email protected]");
}
 
Example 16
Source Project: NFVO   Source File: CustomUserDetailsService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void changePassword(String oldPassword, String newPassword) {
  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  String currentUserName = authentication.getName();
  log.debug("Changing password of user: " + currentUserName);
  User user = userRepository.findFirstByUsername(currentUserName);
  if (!BCrypt.checkpw(oldPassword, user.getPassword())) {
    throw new UnauthorizedUserException("Old password is wrong.");
  }
  if (!(authentication instanceof AnonymousAuthenticationToken)) { // TODO is this line needed?
    user.setPassword(BCrypt.hashpw(newPassword, BCrypt.gensalt(12)));
    userRepository.save(user);
    log.debug("Password of user " + currentUserName + " has been changed successfully.");
  }
}
 
Example 17
Source Project: NFVO   Source File: UserManagement.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public User changePasswordOf(String userName, String newPwd)
    throws PasswordWeakException, NotFoundException {
  User user = userRepository.findFirstByUsername(userName);
  if (user == null) {
    throw new NotFoundException("Not found user " + userName);
  }
  if (checkStrength) {
    Utils.checkPasswordIntegrity(newPwd);
  }
  user.setPassword(BCrypt.hashpw(newPwd, BCrypt.gensalt(12)));
  customUserDetailsService.updateUser(user);
  return user;
}
 
Example 18
Source Project: ReCiter   Source File: ApplicationUserServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean createUser(ApplicationUser appUser) {
	if(appUser.getId() != null
			&& !appUser.getId().isEmpty()
			&& appUser.getUsername() != null
			&& !appUser.getUsername().isEmpty()
			&& appUser.getPassword() != null
			&& !appUser.getPassword().isEmpty()) {
		String password = BCrypt.hashpw(appUser.getPassword(), secretsalt);
		appUser.setPassword(password);
		applicationUserRepository.save(appUser);
		return true;
	}
	return false;
}
 
Example 19
Source Project: besu   Source File: PasswordSubCommand.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
  checkNotNull(parentCommand);

  parentCommand.out.print(BCrypt.hashpw(password, BCrypt.gensalt()));
}
 
Example 20
Source Project: personal_book_library_web_project   Source File: CryptoUtil.java    License: MIT License 4 votes vote down vote up
public static boolean checkPassword(String passwordFromDb, String passwordFromClient) {
	return BCrypt.checkpw(passwordFromDb, passwordFromClient);
}
 
Example 21
Source Project: webFluxTemplate   Source File: CustomPasswordEncoder.java    License: MIT License 4 votes vote down vote up
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
    String decodedString  = new String(Base64.getDecoder().decode(rawPassword.toString()));
    return BCrypt.checkpw(decodedString, encodedPassword);
}
 
Example 22
Source Project: vics   Source File: StrongPasswordEncoder.java    License: MIT License 4 votes vote down vote up
@Override
public String encode(CharSequence rawPassword) {
    return BCrypt.hashpw(rawPassword.toString(), BCrypt.gensalt());
}
 
Example 23
Source Project: vics   Source File: StrongPasswordEncoder.java    License: MIT License 4 votes vote down vote up
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
    return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
}
 
Example 24
Source Project: vics   Source File: UserService.java    License: MIT License 4 votes vote down vote up
private String hashPw(String password) {
    return BCrypt.hashpw(password, BCrypt.gensalt());
}
 
Example 25
Source Project: personal_book_library_web_project   Source File: CryptoUtil.java    License: MIT License 2 votes vote down vote up
public static String cryptPassword(String password) {
	
	return BCrypt.hashpw(password, BCrypt.gensalt());
}
 
Example 26
/**
 * Encode the password.
 *
 * @param rawPassword raw password
 * @return encoded password
 */
@Override public String encode(CharSequence rawPassword) {
  String rawPwd = (String) rawPassword;
  return BCrypt.hashpw(rawPwd, BCrypt.gensalt());
}
 
Example 27
/**
 * Matches raw password and encoded password.
 *
 * @param rawPassword     raw password
 * @param encodedPassword encoded password
 * @return match or not
 */
@Override public boolean matches(CharSequence rawPassword, String encodedPassword) {
  String rawPwd = (String) rawPassword;
  return BCrypt.checkpw(rawPwd, encodedPassword);
}