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

The following examples show how to use org.springframework.security.crypto.bcrypt.BCrypt. 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
Source File: Encryptor.java    From syncope with 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 #2
Source File: CustomUserDetailsService.java    From NFVO with 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 #3
Source File: UserManagement.java    From NFVO with 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 #4
Source File: UserDao.java    From atlas with 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 #5
Source File: ChoerodonBcryptPasswordEncoder.java    From oauth-server with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: ApplicationUserServiceImpl.java    From ReCiter with 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 #7
Source File: Encryptor.java    From syncope with 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 #8
Source File: ApplicationUserServiceImpl.java    From ReCiter with 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 #9
Source File: ChoerodonBcryptPasswordEncoder.java    From oauth-server with Apache License 2.0 5 votes vote down vote up
@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 #10
Source File: CustomPasswordEncoder.java    From webFluxTemplate with 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 #11
Source File: UserDao.java    From atlas with 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
Source File: UserManager.java    From Much-Assembly-Required with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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
Source File: UserManager.java    From Much-Assembly-Required with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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
Source File: UserManager.java    From Much-Assembly-Required with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 File: TomlAuth.java    From besu with 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 #16
Source File: UserManagement.java    From NFVO with 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 #17
Source File: UserBuilder.java    From vics with 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 #18
Source File: CustomUserDetailsService.java    From NFVO with 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 #19
Source File: StrongPasswordEncoder.java    From vics with MIT License 4 votes vote down vote up
@Override
public String encode(CharSequence rawPassword) {
    return BCrypt.hashpw(rawPassword.toString(), BCrypt.gensalt());
}
 
Example #20
Source File: UserService.java    From vics with MIT License 4 votes vote down vote up
private String hashPw(String password) {
    return BCrypt.hashpw(password, BCrypt.gensalt());
}
 
Example #21
Source File: StrongPasswordEncoder.java    From vics with MIT License 4 votes vote down vote up
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
    return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
}
 
Example #22
Source File: CustomPasswordEncoder.java    From webFluxTemplate with 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 #23
Source File: CryptoUtil.java    From personal_book_library_web_project with MIT License 4 votes vote down vote up
public static boolean checkPassword(String passwordFromDb, String passwordFromClient) {
	return BCrypt.checkpw(passwordFromDb, passwordFromClient);
}
 
Example #24
Source File: PasswordSubCommand.java    From besu with 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 #25
Source File: CustomPasswordEncoder.java    From spring-microservice-boilerplate with MIT License 2 votes vote down vote up
/**
 * 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 #26
Source File: CustomPasswordEncoder.java    From spring-microservice-boilerplate with MIT License 2 votes vote down vote up
/**
 * 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);
}
 
Example #27
Source File: CryptoUtil.java    From personal_book_library_web_project with MIT License 2 votes vote down vote up
public static String cryptPassword(String password) {
	
	return BCrypt.hashpw(password, BCrypt.gensalt());
}