下面列出了怎么用org.springframework.security.crypto.bcrypt.BCrypt的API类实例代码及写法,或者点击链接到github查看源代码。
@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;
}
}
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;
}
@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);
}
}
@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;
}
@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;
}
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;
}
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;
}
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"));
}
}
@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;
}
@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);
}
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;
}
/**
* 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());
}
}
/**
* 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"));
}
/**
* 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
}
public UserBuilder withDefaults() {
return withFirstName("Jane")
.withLastName("Doe")
.withWards(newHashSet())
.withConstituencies(newHashSet())
.withPasswordHash(BCrypt.hashpw("password", BCrypt.gensalt()))
.withRole(Role.USER)
.withUsername("[email protected]");
}
@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.");
}
}
@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;
}
@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;
}
@Override
public void run() {
checkNotNull(parentCommand);
parentCommand.out.print(BCrypt.hashpw(password, BCrypt.gensalt()));
}
public static boolean checkPassword(String passwordFromDb, String passwordFromClient) {
return BCrypt.checkpw(passwordFromDb, passwordFromClient);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
String decodedString = new String(Base64.getDecoder().decode(rawPassword.toString()));
return BCrypt.checkpw(decodedString, encodedPassword);
}
@Override
public String encode(CharSequence rawPassword) {
return BCrypt.hashpw(rawPassword.toString(), BCrypt.gensalt());
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
}
private String hashPw(String password) {
return BCrypt.hashpw(password, BCrypt.gensalt());
}
public static String cryptPassword(String password) {
return BCrypt.hashpw(password, BCrypt.gensalt());
}
/**
* 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());
}
/**
* 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);
}