Java org.mindrot.jbcrypt.BCrypt 代码实例

・15 分钟阅读

以下是展示如何使用org.mindrot.jbcrypt.BCrypt的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


@POST
@Path("/create/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String create(@PathParam("repositoryId") String repositoryId, @PathParam("id") String userId,
                @FormParam(FORM_USERNAME) String name, @FormParam(FORM_PASSWORD) String password,
                @FormParam(FORM_FIRSTNAME) String firstName, @FormParam(FORM_LASTNAME) String lastName,
                @FormParam(FORM_EMAIL) String email, @Context HttpServletRequest httpRequest) {
        boolean status = true;
        JSONObject result = new JSONObject();
        JSONArray errMsg = new JSONArray();
        // Validation
        status = validateNewUser(status, errMsg, userId, name, firstName, lastName, password, repositoryId);
        // Create a user
        if (status) {
                // initialize mandatory but space-allowed parameters
                if (StringUtils.isBlank(lastName))
                        lastName = "";
                if (StringUtils.isBlank(email))
                        email = "";
                // Generate a password hash
                String passwordHash = BCrypt.hashpw(password, BCrypt.gensalt());
                User user = new User(userId, name, firstName, lastName, email, passwordHash);
                setFirstSignature(httpRequest, user);
                // TODO Error handling
                principalService.createUser(repositoryId, user);
        }
        result = makeResult(status, result, errMsg);
        return result.toJSONString();
}
 

实例 2


protected MapSqlParameterSource userParams(AdminUser admin) {
    return new MapSqlParameterSource()
            .addValue("username", admin.getUsername())
            .addValue("password", BCrypt.hashpw(admin.getPassword(), BCrypt.gensalt()))
            .addValue("active", admin.isActive())
            .addValue("master", admin.isMaster());
}
 

实例 3


private long createOrganizationAndUser(OrganizationInformation information, OrganizationRegistration registration) {
        try {
                CreateOrganizationRequest req = new CreateOrganizationRequest();
                req.setCountryName(registration.getCountry());
                req.setCurrency(information.getCurrency());
                req.setOrganizationName(registration.getName());
                req.setSubDomain(registration.getEcgineSubDomain());
                String[] packages = getDefaultPackages();
                req.setDefaultPackages(Arrays.asList(packages));
                int organization = organizationCreator.createOrganization(req);
                UserInfo userObj = new UserInfo();
                userObj.setOrgId(organization);
                userObj.setUserName(information.getUserName());
                String password = information.getPassword();
                password = BCrypt.hashpw(password, BCrypt.gensalt());
                userObj.setPassword(password);
                userObj.setEmailId(registration.getEmail());
                userObj.setActive(true);
                long user = userService.createUser(userObj);
                return user;
        } catch (Exception e) {
        }
        return 0;
}
 

实例 4


/**
 * Loads the default users into the database if no User data exists.
 */
@SuppressWarnings("unchecked")
public void loadDefaultUsers() {
    final Session session = sessionFactory.openSession();
    final int count = ((Long) session.createQuery("select count(*) from User ").uniqueResult()).intValue();
    // Check to see if data already exists in the table.
    if (count > 0) {
        session.close();
        return;
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Adding default users to datastore.");
    }
    session.beginTransaction();
    final Query query = session.createQuery(" FROM Roles ");
    final ArrayList<Roles> rolelist = (ArrayList<Roles>) query.list();
    Roles adminRole = null;
    for (Roles role: rolelist) {
        if (role.getRole().equalsIgnoreCase(Roles.ROLE.ADMIN.name())) {
            adminRole = role;
        }
    }
    if (adminRole == null) {
        return;
    }
    final String hashedPassword = BCrypt.hashpw("admin", BCrypt.gensalt(14));
    final User user = new User();
    user.setIsLdap(false);
    user.setPassword(hashedPassword);
    user.setUsername("admin");
    user.setCheckvalid(false);
    user.setRoles(adminRole);
    session.save(user);
    session.getTransaction().commit();
    session.close();
}
 

实例 5


@Produces(MediaType.APPLICATION_JSON)
    @GET
    @Path("/setup")
    public Response setup() throws Exception{
//        logger.info("setup");
//        Credentials user = TestUtils.getTestUser();
//        user = new ServerCredentials(user);
//        user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt(10)));
        ServerCredentials toSave = new ServerCredentials(TestUtils.getTestUser());
//        String en = toSave.getPassword();
//        toSave.decryptPassword(keyManager.getPrivateKey()); //decrypt the password
//        String de = toSave.getPassword();
        String ha = BCrypt.hashpw(toSave.getPassword(), BCrypt.gensalt(10));
        toSave.setPassword(ha); //hash the password for storage
        toSave.setAuthToken(AuthTokenUtils.getNewToken(securityManager.getSymmetricKey(), toSave));
        toSave.setRecoveryToken(AuthTokenUtils.getNewToken(securityManager.getSymmetricKey(), toSave));
        toSave.setOwnerId(dao.count(Credentials.class.getName()) + 1);
        dao.save(toSave);
        return Response.ok().entity(toSave).build();
    }
 

实例 6


private void createAdminUser() {
    User user = new User();
    user.setLogin("admin");
    String hashed = BCrypt.hashpw("admin", BCrypt.gensalt());
    user.setPasswordHash(hashed);
    UserXstreamDao.persist(user);
}
 

实例 7


@Test
public void bcryptTest() {
    String password = PasswordUtils.getRandomPassword();
    String hash = BCrypt.hashpw(password, BCrypt.gensalt(5));
    PasswordResponse response = new PasswordResponse();
    response.setAlgorithm(Algorithm.BCRYPT);
    response.setHash(hash);
    Assert.assertTrue(verifier.verify(password, response));
    Assert.assertFalse(verifier.verify(password + " ", response));
}
 

实例 8


@Test
public void checkingAValidPasswordShouldReturnTrue() {
    // Given
    PasswordSecurity passwordSecurity = new BCryptPasswordSecurity();
    String hashPassword = BCrypt.hashpw(VALID_PASSWORD, BCrypt.gensalt());
    // When
    Boolean check = passwordSecurity.check(VALID_PASSWORD, hashPassword);
    // Then
    assertTrue(check);
}
 

实例 9


private void changePassword(User user, String newPassword)
 {
    log.info("change password for user: " + user.getEmail());
    String hashed = BCrypt.hashpw(newPassword, BCrypt.gensalt());
    user.setPassword(hashed);
    action.apply();
}
 

实例 10


/**
 * Authenticates an user.
 * 
 * @param username User login
 * @param password User password
 * @return ID of the authenticated user or null
 */
public String authenticate(String username, String password) {
    EntityManager em = ThreadLocalContext.get().getEntityManager();
    Query q = em.createQuery("select u from User u where u.username = :username and u.deleteDate is null");
    q.setParameter("username", username);
    try {
        User user = (User) q.getSingleResult();
        if (!BCrypt.checkpw(password, user.getPassword())) {
            return null;
        }
        return user.getId();
    } catch (NoResultException e) {
        return null;
    }
}
 

实例 11


/**
 * Creates a hashed value of a given clear text password and checks if the
 * value matches a given, already hashed password
 *
 * @param password The clear text password
 * @param hash The previously hashed password to check
 * @return True if the new hashed password matches the hash, false otherwise
 */
public boolean authenticate(String password, String hash) {
    Preconditions.checkNotNull(password, "Password is required for authenticate");
    Preconditions.checkNotNull(hash, "Hashed password is required for authenticate");
    boolean authenticated = false;
    try {
        authenticated = BCrypt.checkpw(password, hash);
    } catch (IllegalArgumentException e) {
        LOG.error("Failed to check password against hash", e);
    }
    return authenticated;
}
 

实例 12


public UserApplication verifyLogin(String email, String password) throws UserNotFoundException {
        try {
                UserApplication user = getEntityManager().createQuery(
                                "SELECT u FROM "+UserApplication.class.getSimpleName()+" u WHERE u.email=:email AND u.enabled=TRUE", 
                                UserApplication.class)
                        .setParameter("email", email)
                        .getSingleResult();
                fetch(user.getProfile().getPermissions()); // load permissions from database
                if(BCrypt.checkpw(password, user.getCipheredPassword())){
                        user.setCipheredPassword("");
                        return detach(user);
                }
                throw new UserNotFoundException();
        } catch(NoResultException e){
                throw new UserNotFoundException();
        }
}
 

实例 13


@Override public Optional<User> authenticate(BasicCredentials credentials)
    throws AuthenticationException {
  User user = null;
  String username = credentials.getUsername();
  if (!User.isSanitizedUsername(username)) {
    logger.info("Username: {} must match pattern: {}", username, User.USERNAME_PATTERN);
    return Optional.empty();
  }
  String password = credentials.getPassword();
  // Get hashed password column from BCrypt table by username
  Optional<String> optionalHashedPwForUser = userDAO.getHashedPassword(username);
  if (!optionalHashedPwForUser.isPresent()) {
    return Optional.empty();
  }
  if (BCrypt.checkpw(password, optionalHashedPwForUser.get())) {
    user = User.named(username);
  }
  return Optional.ofNullable(user);
}
 

实例 14


/**
 *  Change Password API
 *
 *  Changes the password for the calling user.
 *
 *  (POST) /api/3/admin/accounts/passchange
 *
 *  Request params: password (string) - The new password
 *
 *  Expected Output: successful pass-changed response if the password was changed, ErrorResponse otherwise
 */
@RequiresAuthentication
@RequestMapping(value = "/passchange", method = RequestMethod.POST)
public Object changePassword(@RequestParam(required = true) String password) {
    String username = getSubjectUsername();
    AdminUser user = adminUserService.getAdminUser(username);
    if (BCrypt.checkpw(password, user.getPassword())) {
        return new ResponseEntity<>(
                new ErrorResponse(ErrorCode.SAME_PASSWORD), HttpStatus.BAD_REQUEST);
    }
    if (password.length() < minPassLength) {
        throw new InvalidRequestParamEx(password.replaceAll(".", "*"), "password", "String",
                "Password must contain at least " + minPassLength + " characters");
    }
    user.setPassword(password);
    adminUserService.createUser(user);
    return new SimpleResponse(true, "Password has been successfully changed", "pass-changed");
}
 

实例 15


/**
 * ?????????????????????
 * 
 * @param rawPassword ?????????
 * @param hashedDbPassword DB??????????????????????????
 * @return ???????
 */
public static boolean checkPassword(String rawPassword, String hashedDbPassword) {
  try {
    return BCrypt.checkpw(rawPassword, hashedDbPassword);
  } catch (Throwable e) {
    return false;
  }
}
 
讨论
淘淘あ西西 profile image