本文整理汇总了Java中org.springframework.security.crypto.bcrypt.BCrypt.hashpw方法的典型用法代码示例。如果您正苦于以下问题:Java BCrypt.hashpw方法的具体用法?Java BCrypt.hashpw怎么用?Java BCrypt.hashpw使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.springframework.security.crypto.bcrypt.BCrypt
的用法示例。
在下文中一共展示了BCrypt.hashpw方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: storeMessage
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
String storeMessage(final String senderId, final String message,
final KeyIv encryptionKey, final List<SecretFile> files,
final byte[] linkSecret, final String password, final Instant expiration) {
Objects.requireNonNull(senderId, "senderId must not be null");
final String receiverId = newRandomId();
final String hashedPassword =
password != null ? BCrypt.hashpw(password, BCrypt.gensalt()) : null;
final ReceiverMessage receiverMessage = new ReceiverMessage(
receiverId,
senderId,
hashedPassword,
encryptKey(linkSecret,
MoreObjects.firstNonNull(password, DEFAULT_PASSWORD), encryptionKey),
encryptMessage(message, encryptionKey.getKey()),
files,
expiration
);
receiverMsgRepository.create(receiverId, receiverMessage);
return receiverId;
}
示例2: encode
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
public String encode(final String value, final CipherAlgorithm cipherAlgorithm)
throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
String encodedValue = null;
if (value != null) {
if (cipherAlgorithm == null || cipherAlgorithm == CipherAlgorithm.AES) {
final byte[] cleartext = value.getBytes(StandardCharsets.UTF_8);
final Cipher cipher = Cipher.getInstance(CipherAlgorithm.AES.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
encodedValue = new String(Base64.getEncoder().encode(cipher.doFinal(cleartext)));
} else if (cipherAlgorithm == CipherAlgorithm.BCRYPT) {
encodedValue = BCrypt.hashpw(value, BCrypt.gensalt());
} else {
encodedValue = getDigester(cipherAlgorithm).digest(value);
}
}
return encodedValue;
}
示例3: encryptField
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
private String encryptField(String plainValue, String encryptionType) {
if (ONE_WAY_HINT.equals(encryptionType)) {
String salt = BCrypt.gensalt();
String encryptedValue = BCrypt.hashpw(plainValue, salt);
return encryptedValue;
} else if (TWO_WAY_HINT.equals(encryptionType)) {
try {
return Base64.encodeBase64String(plainValue.getBytes(CHARSET));
} catch (UnsupportedEncodingException exception) {
System.out.println("[easy-men] problem with the encoding " + CHARSET);
return null;
}
// // AES encryption, requires Java7
// String salt = KeyGenerators.string().generateKey();
// TextEncryptor textEncryptor = Encryptors.queryableText(_password, salt);
// return new StringBuilder(textEncryptor.encrypt(plainValue)).append(":").append(salt).toString();
}
return null;
}
示例4: updateAuthenticationDetails
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
/**
* Updates the modelwrapper authentication details.
* @param username The new username.
* @param password The new password.
* @param passwordConfirmation Confirmation of the new password.
* @return 204 for success, 400 for failure.
*/
@RequestMapping(value = "/auth", method = RequestMethod.POST)
public ResponseEntity updateAuthenticationDetails(String username, String password, String passwordConfirmation) {
boolean validRequest =
!StringUtils.isEmpty(username) && USERNAME_REGEX.matcher(username).matches() &&
!StringUtils.isEmpty(password) && PASSWORD_REGEX.matcher(password).matches() &&
password.equals(passwordConfirmation);
if (validRequest) {
String passwordHash = BCrypt.hashpw(password, BCrypt.gensalt());
configurationService.setAuthenticationDetails(username, passwordHash);
// Respond with a 204, this is equivalent to a 200 (OK) but without any content.
return new ResponseEntity(HttpStatus.NO_CONTENT);
} else {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
示例5: approveAccount
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
/**
* Assume password has been set as plain text
* @param account
*/
public void approveAccount(final Account account) {
this.logger.info("AccountService.approveAccount");
// Create random salt and store a hashed password
final String textPassword = account.getHashedPass();
final String salt = BCrypt.gensalt(16);
final String hashedPassword = BCrypt.hashpw(textPassword, salt);
account.setSalt(salt);
account.setHashedPass(hashedPassword);
// status is now approved
account.setStatus(AccountStatus.STATUS_APPROVED.name());
this.accountRepo.save(account);
}
示例6: createHash
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
@Override
public String createHash(String password) throws CustomException {
logger.trace("Création du Hash avec BCrypt");
String pwd = BCrypt.hashpw(password, BCrypt.gensalt());
if (pwd.length()>150){
throw new CustomException();
}
return pwd;
}
示例7: create
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
/**
* Create a user with specified CLEAR password.
*
* @param username
* @param clearPassword
* @param role
* @return
* @throws IOException
*/
public User create(String username, String clearPassword, Role role) throws IOException {
username = username.trim().toLowerCase();
String hashedPassword = BCrypt.hashpw(clearPassword, HASH_SALT);
User cred = new User(username, hashedPassword, role);
try {
dao.create(cred);
return cred;
} catch (SQLException e) {
throw new IOException(e);
}
}
示例8: testHashpwAndCheckpw
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
@Test
public void testHashpwAndCheckpw()
{
String password = "student";
// Hash a password using the OpenBSD bcrypt scheme
String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
System.out.println(hashedPassword);
// Check that a plaintext password matches a previously hashed one
Assert.assertTrue(BCrypt.checkpw("student", hashedPassword));
}
示例9: register
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseBody
public LoggedUserModel register(@RequestBody UserRegisterModel userRegModel)
throws InvalidActivityException {
this.validateUsername(userRegModel.getUsername());
this.validatePassword(userRegModel.getPassword());
this.validateEmail(userRegModel.getEmail());
UserModel user = userService.getUserByUsername(userRegModel
.getUsername());
if (user != null) {
throw new InvalidActivityException("The username is already taken!");
}
String hashedPassword = BCrypt.hashpw(userRegModel.getPassword(),
BCrypt.gensalt());
userRegModel.setPassword(hashedPassword);
user = this.userRegisterModelToUserModel(userRegModel);
userService.add(user);
user = userService.getUserByUsername(user.getUsername());
user.setSessionKey(this.generateSessionKey(user.getId()));
userService.update(user);
LoggedUserModel loggedUser = new LoggedUserModel();
loggedUser.setUsername(user.getUsername());
loggedUser.setSessionKey(user.getSessionKey());
loggedUser.setId(user.getId());
return loggedUser;
}
示例10: settingsPut
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
@PreAuthorize("hasAuthority('hungry')")
public void settingsPut(Settings upUser) throws ApiException {
com.jrtechnologies.yum.data.entity.User userDAO = userRepo.findById((Long) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
if (upUser == null) {
throw new ApiException(400, "Bad Request");
} else if (upUser.getLastEdit().getVersion() != userDAO.getVersion()) // checks the version. It must be the same
{
UserSettings userSettingsDTO = new UserSettings();
userSettingsDTO.setFirstName(userDAO.getFirstName());
userSettingsDTO.setLastName(userDAO.getLastName());
userSettingsDTO.setEmail(userDAO.getEmail());
userSettingsDTO.setRole(userDAO.getUserRole().toString());
userSettingsDTO.setLastEdit(new LastEdit(userDAO.getLastEdit(), userDAO.getVersion()));
userSettingsDTO.setOrderNtf(userDAO.isOrderNtf());
userSettingsDTO.setOrderModifyNtf(userDAO.isOrderModifyNtf());
userSettingsDTO.setAdminOrderNtf(userDAO.isAdminOrderNtf());
userSettingsDTO.setAdminOrderModifyNtf(userDAO.isAdminOrderModifyNtf());
userSettingsDTO.setBalanceNtf(userDAO.isBalanceNtf());
throw new ConcurrentModificationException(409, "Concurrent modification error.", userSettingsDTO);
} else {
//Check if name is empty.
String firstName = upUser.getFirstName().trim();
String lastName = upUser.getLastName().trim();
if (firstName.equals("") || lastName.equals("")) {
throw new ApiException(400, "User couldn't be updated");
}
if (upUser.getFirstName() != null && !firstName.equals(userDAO.getFirstName())) {
if ((firstName.length()) < 0 || (firstName.length()) > 50) {
throw new ApiException(400, "First Name not valid"); // First Name's length should be >1 && <50
}
}
if (upUser.getLastName() != null && !lastName.equals(userDAO.getLastName())) {
if ((lastName.length()) < 0 || (lastName.length()) > 50) {
throw new ApiException(400, "Last Name not valid"); // Last Name's length should be >1 && <50
}
}
String newPassword = upUser.getPassword().trim();
// System.out.println("newPassword: " + newPassword);
String newPasswordEncrypt = "";
if (newPassword != null && !newPassword.equals("")){
newPasswordEncrypt = BCrypt.hashpw(newPassword, BCrypt.gensalt());
if ((!newPasswordEncrypt.equals(userDAO.getPassword())) && ((newPassword.length()) < 6)) {
throw new ApiException(400, "Password not valid"); // Password's length should be >6
}
}
//If there are no invalid inputs, the new data will be update
if (upUser.getFirstName() != null && !upUser.getFirstName().trim().equals(userDAO.getFirstName())) {
userDAO.setFirstName(upUser.getFirstName().trim());
}
if (upUser.getLastName() != null && !upUser.getLastName().trim().equals(userDAO.getLastName())) {
userDAO.setLastName(upUser.getLastName().trim());
}
if (upUser.getPassword() != null && !newPassword.equals("") && !newPasswordEncrypt.equals(userDAO.getPassword())) {
userDAO.setPassword(newPasswordEncrypt);
}
if (upUser.getEmail() != null && !upUser.getEmail().trim().equals(userDAO.getEmail())) {
if (userRepo.findByEmail(upUser.getEmail()) != null) {
throw new ApiException(412, "User email already exists");
}
userDAO.setEmail(upUser.getEmail());
}
userDAO.setOrderNtf(upUser.getOrderNtf());
userDAO.setOrderModifyNtf(upUser.getOrderModifyNtf());
userDAO.setAdminOrderNtf(upUser.getAdminOrderNtf());
userDAO.setAdminOrderModifyNtf(upUser.getAdminOrderModifyNtf());
userDAO.setBalanceNtf(upUser.getBalanceNtf());
}
}
示例11: generateHash
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
public String generateHash(String text) {
String newPasswordHash = BCrypt.hashpw(text, BCrypt.gensalt());
return newPasswordHash;
}
示例12: encode
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
@Override
public String encode(CharSequence rawPassword) {
return BCrypt.hashpw(rawPassword.toString(), BCrypt.gensalt());
}
示例13: hashPw
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
private String hashPw(String password) {
return BCrypt.hashpw(password, BCrypt.gensalt());
}
示例14: retrieveUser
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
@Override public UserDetails retrieveUser(final String name, final UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
this.logger.info("MongoDBAuthenticationProvider.retrieveUser");
boolean valid = true;
// Make sure an actual password was entered
final String password = (String)authentication.getCredentials();
if (!StringUtils.hasText(password)) {
this.logger.warn("Username {}: no password provided", name);
valid = false;
}
// Look for user and check their account is activated
final Account account = this.accountService.getByName(name);
if (account == null) {
this.logger.warn("Username {}: user not found", name);
valid = false;
} else {
if (!AccountStatus.STATUS_APPROVED.name().equals(account.getStatus())) {
this.logger.warn("Username {}: not approved", name);
valid = false;
}
// Check password
final String hashedPassword = BCrypt.hashpw(password, account.getSalt());
if (!hashedPassword.equals(account.getHashedPass())) {
this.logger.warn("Username {}: bad password entered", name);
valid = false;
}
}
if (!valid) {
final Locale locale = LocaleContextHolder.getLocale();
final String message = this.messageSource.getMessage("exception.wrongAccountNameAndPass", null, locale);
final MessageBox messageBox = new MessageBox("wrongAccountNameAndPass", message, new ArrayList<String>());
final List<MessageBox> errorMessages = new ArrayList<MessageBox>();
errorMessages.add(messageBox);
final LoginException loginException = new LoginException(errorMessages, name);
throw new BadCredentialsException("Invalid Username/Password", loginException);
}
// Create Springframework-typed User instance
final List<String> roles = account.getRoles();
final List<GrantedAuthority> auths = !roles.isEmpty() ? AuthorityUtils.commaSeparatedStringToAuthorityList(account.getRolesCSV()) : AuthorityUtils.NO_AUTHORITIES;
// enabled, account not expired, credentials not expired, account not locked
return new User(name, password, true, true, true, true, auths);
}
示例15: setPassword
import org.springframework.security.crypto.bcrypt.BCrypt; //导入方法依赖的package包/类
public void setPassword(String password) {
if (!password.startsWith("$2a$")) {
this.password = BCrypt.hashpw(password, BCrypt.gensalt());
}
}