Java Examples for org.springframework.security.crypto.bcrypt.BCrypt
The following java examples will help you to understand the usage of org.springframework.security.crypto.bcrypt.BCrypt. These source code samples are taken from different open source projects.
Example 1
| Project: ABRAID-MP-master File: IndexController.java View source code |
/**
* 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);
}
}Example 2
| Project: JAppJUp-master File: BCryptAuthenticationManager.java View source code |
/**
* Authenticate user.
*
* @param auth
* authentication data passed by Spring Security
* @return result of authentication
*/
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
logger.debug("Performing authentication");
User user = null;
logger.debug("Searching user [" + auth.getName() + "] in DB");
try {
user = userService.findByUsername(auth.getName());
} catch (Exception e) {
logger.error("User [" + auth.getName() + "] does not exists (exception)!");
throw new AuthenticationServiceException("Error while obtaining User data!");
}
if (user == null) {
logger.error("User [" + auth.getName() + "] does not exists (null)!");
throw new BadCredentialsException("User does not exists!");
}
if (!BCrypt.checkpw(auth.getCredentials().toString(), user.getHashedPassword())) {
logger.error("Password doesn't match!");
throw new BadCredentialsException("Password doesn't match!");
}
logger.debug("User details are good and ready to go");
return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(), getAuthorities(user.isAdmin(), user.isPackageAdmin()));
}Example 3
| Project: uaa-master File: CachingPasswordEncoder.java View source code |
private boolean internalMatches(String cacheKey, CharSequence rawPassword, String encodedPassword) {
Set<String> cacheValue = cache.getIfPresent(cacheKey);
boolean result = false;
List<String> searchList = (cacheValue != null ? new ArrayList(cacheValue) : Collections.<String>emptyList());
for (String encoded : searchList) {
if (hashesEquals(encoded, encodedPassword)) {
result = true;
break;
}
}
if (!result) {
String encoded = BCrypt.hashpw(rawPassword.toString(), encodedPassword);
if (hashesEquals(encoded, encodedPassword)) {
result = true;
cacheValue = getOrCreateHashList(cacheKey);
if (cacheValue != null) {
//Only if you store multiple versions of the same password more than once
if (cacheValue.size() >= getMaxEncodedPasswords()) {
cacheValue.clear();
}
cacheValue.add(encoded);
}
}
}
return result;
}Example 4
| Project: alien4cloud-master File: UserService.java View source code |
/**
* Create a new internal user and saves it.
*
* @param userName The userName of the new user.
* @param email The email of the new user.
* @param firstName The firstName of the new user.
* @param lastName The lastname of the new user.
* @param roles The roles of the new user.
* @param password The password of the new user (hash only will be saved).
*/
public void createUser(String userName, String email, String firstName, String lastName, String[] roles, String password) {
if (alienUserDao.find(userName) != null) {
throw new AlreadyExistException("A user with the given username already exists.");
}
User user = new User();
user.setUsername(userName);
user.setEmail(email);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setRoles(roles);
user.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));
user.setInternalDirectory(true);
user.setEnabled(true);
user.setAccountNonExpired(true);
user.setAccountNonLocked(true);
user.setCredentialsNonExpired(true);
alienUserDao.save(user);
}Example 5
| Project: syncope-master File: Encryptor.java View source code |
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.encode(cipher.doFinal(cleartext)));
} else if (cipherAlgorithm == CipherAlgorithm.BCRYPT) {
encodedValue = BCrypt.hashpw(value, BCrypt.gensalt());
} else {
encodedValue = getDigester(cipherAlgorithm).digest(value);
}
}
return encodedValue;
}Example 6
| Project: cas-overlay-master File: OpenScienceFrameworkAuthenticationHandler.java View source code |
/**
* Verify Password. `bcrypt$` (backward compatibility) and `bcrypt_sha256$` are the only two valid prefix.
*
* @param plainTextPassword the plain text password provided by the user
* @param userPasswordHash the password hash stored in database
* @return True if verified, False otherwise
*/
private boolean verifyPassword(final String plainTextPassword, final String userPasswordHash) {
String password, passwordHash;
try {
if (userPasswordHash.startsWith("bcrypt$")) {
// django.contrib.auth.hashers.BCryptPasswordHasher
passwordHash = userPasswordHash.split("bcrypt\\$")[1];
password = plainTextPassword;
} else if (userPasswordHash.startsWith("bcrypt_sha256$")) {
// django.contrib.auth.hashers.BCryptSHA256PasswordHasher
passwordHash = userPasswordHash.split("bcrypt_sha256\\$")[1];
password = sha256HashPassword(plainTextPassword);
} else {
// invalid password hash prefix
return false;
}
passwordHash = updateBCryptHashIdentifier(passwordHash);
return password != null && passwordHash != null && BCrypt.checkpw(password, passwordHash);
} catch (final Exception e) {
logger.error(String.format("CAS has encountered a problem when verifying the password: %s.", e.toString()));
return false;
}
}Example 7
| Project: authentication-master File: BCrypt.java View source code |
/** * Hash a password using the OpenBSD bcrypt scheme * @param password the password to hash * @param salt the salt to hash with (perhaps generated * using BCrypt.gensalt) * @return the hashed password */ public static String hashpw(String password, String salt) { BCrypt B; String real_salt; byte passwordb[], saltb[], hashed[]; char minor = (char) 0; int rounds, off = 0; StringBuilder rs = new StringBuilder(); int saltLength = salt.length(); if (saltLength < 28) { throw new IllegalArgumentException("Invalid salt"); } if (salt.charAt(0) != '$' || salt.charAt(1) != '2') { throw new IllegalArgumentException("Invalid salt version"); } if (salt.charAt(2) == '$') { off = 3; } else { minor = salt.charAt(2); if (minor != 'a' || salt.charAt(3) != '$') { throw new IllegalArgumentException("Invalid salt revision"); } off = 4; } if (saltLength - off < 25) { throw new IllegalArgumentException("Invalid salt"); } // Extract number of rounds if (salt.charAt(off + 2) > '$') { throw new IllegalArgumentException("Missing salt rounds"); } rounds = Integer.parseInt(salt.substring(off, off + 2)); real_salt = salt.substring(off + 3, off + 25); try { passwordb = (password + (minor >= 'a' ? "\000" : "")).getBytes("UTF-8"); } catch (UnsupportedEncodingException uee) { throw new AssertionError("UTF-8 is not supported"); } saltb = decode_base64(real_salt, BCRYPT_SALT_LEN); B = new BCrypt(); hashed = B.crypt_raw(passwordb, saltb, rounds); rs.append("$2"); if (minor >= 'a') { rs.append(minor); } rs.append("$"); if (rounds < 10) { rs.append("0"); } rs.append(rounds); rs.append("$"); encode_base64(saltb, saltb.length, rs); encode_base64(hashed, bf_crypt_ciphertext.length * 4 - 1, rs); return rs.toString(); }
Example 8
| Project: quadriga-master File: UserManager.java View source code |
private String encryptPassword(String password) {
return BCrypt.hashpw(password, BCrypt.gensalt());
}