当前位置: 首页>>代码示例>>Java>>正文


Java BCrypt类代码示例

本文整理汇总了Java中org.mindrot.jbcrypt.BCrypt的典型用法代码示例。如果您正苦于以下问题:Java BCrypt类的具体用法?Java BCrypt怎么用?Java BCrypt使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


BCrypt类属于org.mindrot.jbcrypt包,在下文中一共展示了BCrypt类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: createUser

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
@Transactional
public User createUser(String username, String firstName, String lastName, String email, String password,
                       String affiliation) {
    User user = new User();

    user.setUsername(username);
    user.setFirstname(firstName);
    user.setLastname(lastName);
    user.setEmail(email);
    user.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));
    user.setRoles(Collections.singletonList(SecurityRole.findByName(DEFAULT_ROLE)));
    user.setAffiliation(affiliation);
    user.setCreatedOn(new Date());

    user.save();
    return user;
}
 
开发者ID:kurator-org,项目名称:kurator-web,代码行数:18,代码来源:UserDao.java

示例2: userSignUp

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
public Credentials userSignUp(Credentials credentials) throws DAOException{
    if (getUserByEmail(dao,credentials.getEmailAddress())!=null){
        throw new DAOException(HttpStatus.SC_CONFLICT,"User Already Exists");
    }
    ServerCredentials toSave = new ServerCredentials(credentials);

    toSave.decryptPassword(keyManager.getPrivateKey()); //decrypt the password
    String de = toSave.getPassword();
    String ha = BCrypt.hashpw(de, BCrypt.gensalt(10));

    toSave.setOwnerId(dao.count(Credentials.class.getName()) + 1);
    toSave.setPassword(ha); //hash the password for storage
    toSave.setAuthToken(AuthTokenUtils.getNewToken(keyManager.getSymmetricKey(), toSave));
    toSave.setRecoveryToken(AuthTokenUtils.getNewToken(keyManager.getSymmetricKey(), toSave));

    dao.save(toSave);

    return toSave;
}
 
开发者ID:williamwebb,项目名称:divide,代码行数:20,代码来源:AuthServerLogic.java

示例3: login

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
/**
 * Logs in the user with email address and password.
 * Returns the user on success.
 *
 * @param email The user's email address.
 * @param password The user's plain text password.
 * @return the user details.
 */
public NewCookie login(final String email, final String password) {
    final SecurityUser candidate = dao.findUserByEmail(userClass, email);
    if (candidate == null) {
        throw new BadRequestException("notfound");
    }

    if (candidate.getPasswordHash() == null) {
        throw new BadRequestException("invalid");
    }

    if (!BCrypt.checkpw(password, candidate.getPasswordHash())) {
        throw new BadRequestException("incorrect");
    }

    return loginAs(candidate);
}
 
开发者ID:minijax,项目名称:minijax,代码行数:25,代码来源:Security.java

示例4: changePassword

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
/**
 * Changes the current user's password.
 *
 * @param oldPassword The old password.
 * @param newPassword The new password.
 * @param confirmNewPassword The confirmed new password.
 */
public void changePassword(final String oldPassword, final String newPassword, final String confirmNewPassword) {
    requireLogin();

    if (user.getPasswordHash() == null) {
        throw new BadRequestException("unset");
    }

    if (!BCrypt.checkpw(oldPassword, user.getPasswordHash())) {
        throw new BadRequestException("incorrect");
    }

    if (!newPassword.equals(confirmNewPassword)) {
        throw new BadRequestException("mismatch");
    }

    if (newPassword.length() < MINIMUM_PASSWORD_LENGTH) {
        throw new BadRequestException("short");
    }

    user.setPassword(newPassword);
    dao.update(user);
}
 
开发者ID:minijax,项目名称:minijax,代码行数:30,代码来源:Security.java

示例5: authenticate

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
/**
 * Performs authentication on the provided employee.
 *
 * @param employeeId The id number of the employee to authenticate.
 *
 * @param plaintextPassword The plaintext password of the employee.
 *
 * @return The appropriate authenticationResult enum type.
 */
public AuthenticationResult authenticate(Long employeeId, String plaintextPassword) {
    Employee employee = getEmployeeById(employeeId);
    String hashed; // The encrypted (hashed) password of the employee.
    try {
        hashed = employee.getHashedPassword();
    } catch (EntityNotFoundException e) {
        return AuthenticationResult.FAILURE;
    }

    boolean passwordCorrect = BCrypt.checkpw(plaintextPassword, hashed);
    if(passwordCorrect) {
        return AuthenticationResult.SUCCESS;
    } else {
        return AuthenticationResult.FAILURE;
    }
}
 
开发者ID:maillouxc,项目名称:git-rekt,代码行数:26,代码来源:EmployeeService.java

示例6: testUsers

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
@Test
public void testUsers() throws Exception {
    //FileUserController.load();
    IUser user = new User();
    user.setEmail("[email protected]");
    user.setBcryptedPassword(BCrypt.hashpw("foxywords", BCrypt.gensalt()));
    user.setUsername(user.getEmail());
    user.setFamilyName("Von Colt");
    user.setGivenName("Wolfgang");
    UserController.instance().save(user);

    User existing = (User) UserController.instance().forId(user.getId());
    Assert.assertEquals(existing.getEmail(), user.getEmail());

    existing = (User) UserController.instance().forUniqueKey("email", user.getEmail());
    Assert.assertEquals(user.getGivenName(), existing.getGivenName());


}
 
开发者ID:StallionCMS,项目名称:stallion-core,代码行数:20,代码来源:UsersTests.java

示例7: updateUser

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
@Transactional
public User updateUser(String email, String username, String firstName, String lastName, String password,
                       String affiliation) {
    User user = User.find.where().eq("email", email).findUnique();

    user.setUsername(username);
    user.setFirstname(firstName);
    user.setLastname(lastName);
    user.setEmail(email);
    user.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));
    user.setRoles(Collections.singletonList(SecurityRole.findByName(DEFAULT_ROLE)));
    user.setAffiliation(affiliation);
    user.setLastActive(new Date());

    user.update();
    return user;
}
 
开发者ID:kurator-org,项目名称:kurator-web,代码行数:18,代码来源:UserDao.java

示例8: changePassword

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
public Result changePassword() {
    Form<ChangePass> form = formFactory.form(ChangePass.class).bindFromRequest();

    if (form.hasErrors()) {
        return badRequest(settings.render(form));
    }

    ChangePass changePass = form.get();

    // Get the currently logged in user
    long uid = Long.parseLong(session().get("uid"));
    User user = User.find.byId(uid);

    // Update the password
    String pass = changePass.getPassword();
    String hash = BCrypt.hashpw(pass, BCrypt.gensalt());

    user.setPassword(hash);
    user.save();

    flash("message", "Successfully updated your password.");

    return redirect(
            routes.Application.settings()
    );
}
 
开发者ID:kurator-org,项目名称:kurator-web,代码行数:27,代码来源:Users.java

示例9: setPassword

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
@Override
public void setPassword(String password) {
	if (((getEncryption() == 0) || (!password.equalsIgnoreCase(getPassword()))) && (_um != null)) {
		String pass;
		switch (_um.getPasscrypt()) {
			case 1: pass = Encrypt(password,"MD2"); setEncryption(1); break;
			case 2: pass = Encrypt(password,"MD5"); setEncryption(2); break;
			case 3: pass = Encrypt(password,"SHA-1"); setEncryption(3); break;
			case 4: pass = Encrypt(password,"SHA-256"); setEncryption(4); break;
			case 5: pass = Encrypt(password,"SHA-384"); setEncryption(5); break;
			case 6: pass = Encrypt(password,"SHA-512"); setEncryption(6); break;
			case 7: pass = BCrypt.hashpw(password, BCrypt.gensalt(_workload)); setEncryption(7); break;
			default: pass = password; setEncryption(0); break;
		}

		if (pass != null) {
			if (pass.length() < 2) {
				logger.debug("Failed To Set Password, Length Too Short");
			} else {
				super.setPassword(pass);
			}
		}
	} else {
		super.setPassword(password);
	}
}
 
开发者ID:drftpd-ng,项目名称:drftpd3,代码行数:27,代码来源:EncryptedBeanUser.java

示例10: getUser

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
public static Optional<UserPermission> getUser(String username, String password) {
    if (username == null || password == null || !users.containsKey(username)) {
        return Optional.empty();
    }

    try {
        UserPermission perm = users.get(username);
        if (!BCrypt.checkpw(password, perm.getPassword())) {
            return Optional.empty();
        }

        return Optional.of(perm);
    } catch (IllegalArgumentException ignored) {
        return Optional.empty();
    }
}
 
开发者ID:Valandur,项目名称:Web-API,代码行数:17,代码来源:Users.java

示例11: login

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
/**
 * Login method which tries to lookup user with given email and password.
 *
 * @return Redirection link.
 */
public String login() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    User user = userService.findByEmail(email);
    if (user == null || user.getPassword() == null
            || !BCrypt.checkpw(password, user.getPassword())) {
        ResourceBundle bundle = ResourceBundle.getBundle("messages",
                facesContext.getViewRoot().getLocale());
        facesContext.addMessage(null, new FacesMessage(FacesMessage
                .SEVERITY_FATAL, bundle.getString("common.error"),
                bundle.getString("login.fail")));
        return "";
    }
    user.setLastActivity(DateUtil.getDateTime());
    user = userService.update(user);
    facesContext.getExternalContext().getSessionMap().put(Constants.SESSION_MAP_KEY_USER, user);
    return PATH_TO_COURSE_OVERVIEW;
}
 
开发者ID:stefanoberdoerfer,项目名称:exmatrikulator,代码行数:23,代码来源:LoginController.java

示例12: initUserFromInput

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
/**
 * Initialises the user object from the user input.
 * @Pre The user input(email,password,firstname,lastname) is valid.
 * @return The generated registered User Object.
 */
private User initUserFromInput() {
    final String hashPW = BCrypt.hashpw(password, BCrypt.gensalt());
    final User newUser = new User();

    /* Don't set language here. Only set the language column if the user
     * explicitly requested it by changing his settings. JSF determines the
     * locale it should use by looking at the HTTP Accept-Language Header.
     * If it isn't set it uses the default-locale set in our
     * faces-config.xml. */

    newUser.setEmail(email);
    newUser.setPassword(hashPW);
    newUser.setFirstName(firstName);
    newUser.setLastName(lastName);
    newUser.setSalutation(salutation);
    newUser.setMatriculationNumber(matriculationNumber);
    newUser.addRole(GlobalRole.USER);
    newUser.setLastActivity(DateUtil.getDateTime());
    return newUser;
}
 
开发者ID:stefanoberdoerfer,项目名称:exmatrikulator,代码行数:26,代码来源:RegistrationController.java

示例13: respondWith200_whenCreateAToken_ifProvidedBothAccountIdAndDescription

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
@Test
public void respondWith200_whenCreateAToken_ifProvidedBothAccountIdAndDescription() throws Exception {
    String newToken = createTokenFor(validTokenPayload)
            .statusCode(200)
            .body("token", is(notNullValue()))
            .extract().path("token");

    int apiKeyHashSize = 32;
    String tokenApiKey = newToken.substring(0, newToken.length() - apiKeyHashSize);
    String hashedToken = BCrypt.hashpw(tokenApiKey, SALT);

    Optional<String> newTokenDescription = app.getDatabaseHelper().lookupColumnForTokenTable("description", TOKEN_HASH_COLUMN, hashedToken);

    assertThat(newTokenDescription.get(), equalTo(TOKEN_DESCRIPTION));

    Optional<String> newTokenAccountId = app.getDatabaseHelper().lookupColumnForTokenTable("account_id", TOKEN_HASH_COLUMN, hashedToken);
    assertThat(newTokenAccountId.get(), equalTo(ACCOUNT_ID));

    Optional<String> newCreatedByEmail = app.getDatabaseHelper().lookupColumnForTokenTable("created_by", TOKEN_HASH_COLUMN, hashedToken);
    assertThat(newCreatedByEmail.get(), equalTo(USER_EMAIL));

    Optional<String> newTokenType = app.getDatabaseHelper().lookupColumnForTokenTable("token_type", TOKEN_HASH_COLUMN, hashedToken);
    assertThat(newTokenType.get(), equalTo(CARD.toString()));
}
 
开发者ID:alphagov,项目名称:pay-publicauth,代码行数:25,代码来源:PublicAuthResourceITest.java

示例14: authenticate

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
@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);
}
 
开发者ID:square,项目名称:keywhiz,代码行数:24,代码来源:BcryptAuthenticator.java

示例15: updateUser

import org.mindrot.jbcrypt.BCrypt; //导入依赖的package包/类
@Override
public String updateUser(final String userName, final String emailAddress, final String hashedPassword) {
  final INode remote = MessageContext.getSender();
  if (!userName.equals(remote.getName())) {
    logger.severe("Tried to update user permission, but not correct user, userName:" + userName + " node:" + remote);
    return "Sorry, but I can't let you do that";
  }

  final DBUser user = new DBUser(
      new DBUser.UserName(userName),
      new DBUser.UserEmail(emailAddress));
  if (!user.isValid()) {
    return user.getValidationErrorMessage();
  }
  final HashedPassword password = new HashedPassword(hashedPassword);

  try {
    new UserController().updateUser(user,
        password.isHashedWithSalt() ? password : new HashedPassword(BCrypt.hashpw(hashedPassword, BCrypt.gensalt())));
  } catch (final IllegalStateException e) {
    return e.getMessage();
  }
  return null;
}
 
开发者ID:triplea-game,项目名称:triplea,代码行数:25,代码来源:UserManager.java


注:本文中的org.mindrot.jbcrypt.BCrypt类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。