org.mindrot.jbcrypt.BCrypt Java Examples
The following examples show how to use
org.mindrot.jbcrypt.BCrypt.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestEndpoint.java From divide with Apache License 2.0 | 6 votes |
@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(); }
Example #2
Source File: UsersServiceImplTest.java From realworld-api-quarkus with MIT License | 6 votes |
@Test public void givenValidNewUserData_thenReturnAnCreatedUserWithFilledTokenField() { String username = "user"; String email = "[email protected]"; String password = "user123"; User createdUser = new User(); createdUser.setId(1L); createdUser.setUsername(username); createdUser.setEmail(email); createdUser.setPassword(BCrypt.hashpw(password, BCrypt.gensalt())); createdUser.setToken(UUID.randomUUID().toString()); when(userRepository.create(any(User.class))).thenReturn(createdUser); when(tokenProvider.createUserToken(createdUser.getId().toString())).thenReturn("token"); User resultUser = usersService.create(username, email, password); Assertions.assertNotNull(resultUser.getUsername()); Assertions.assertNotNull(resultUser.getEmail()); Assertions.assertNotNull(resultUser.getPassword()); Assertions.assertNotNull(resultUser.getToken()); }
Example #3
Source File: UserService.java From Web-API with MIT License | 6 votes |
public Optional<UserPermissionStruct> getUser(String username, String password) { if (username == null || password == null || !users.containsKey(username)) { return Optional.empty(); } try { UserPermissionStruct perm = users.get(username); if (!BCrypt.checkpw(password, perm.getPassword())) { return Optional.empty(); } return Optional.of(perm); } catch (IllegalArgumentException ignored) { return Optional.empty(); } }
Example #4
Source File: AuthController.java From tutorials with MIT License | 6 votes |
@Post("/login") public void login(HttpServletRequest request) { String password = request.getParameter("user.password"); String email = request.getParameter("user.email"); if(email.isEmpty() || password.isEmpty()) { result.include("error", "Email/Password is Required!"); result.redirectTo(AuthController.class).loginForm(); } User user = userDao.findByEmail(email); if(user != null && BCrypt.checkpw(password, user.getPassword())) { userInfo.setUser(user); result.include("status", "Login Successful!"); result.redirectTo(IndexController.class).index(); } else { result.include("error", "Email/Password Does Not Match!"); result.redirectTo(AuthController.class).loginForm(); } }
Example #5
Source File: SimpleAuthenticator.java From tinkerpop with Apache License 2.0 | 6 votes |
public AuthenticatedUser authenticate(final Map<String, String> credentials) throws AuthenticationException { final Vertex user; if (!credentials.containsKey(PROPERTY_USERNAME)) throw new IllegalArgumentException(String.format("Credentials must contain a %s", PROPERTY_USERNAME)); if (!credentials.containsKey(PROPERTY_PASSWORD)) throw new IllegalArgumentException(String.format("Credentials must contain a %s", PROPERTY_PASSWORD)); final String username = credentials.get(PROPERTY_USERNAME); final String password = credentials.get(PROPERTY_PASSWORD); final CredentialTraversal<Vertex,Vertex> t = credentialStore.users(username); if (!t.hasNext()) throw new AuthenticationException("Username and/or password are incorrect"); user = t.next(); if (t.hasNext()) { logger.warn("There is more than one user with the username [{}] - usernames must be unique", username); throw new AuthenticationException("Username and/or password are incorrect"); } final String hash = user.value(PROPERTY_PASSWORD); if (!BCrypt.checkpw(password, hash)) throw new AuthenticationException("Username and/or password are incorrect"); return new AuthenticatedUser(username); }
Example #6
Source File: AuthServerLogic.java From divide with Apache License 2.0 | 6 votes |
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; }
Example #7
Source File: AppCrypto.java From actframework with Apache License 2.0 | 5 votes |
/** * Verify a password against given hash. * * Note this method uses {@link act.conf.AppConfigKey#SECRET confiured application secret} * * @param password the password to be verified. * @param hash the hash used to verify the password * @return `true` if the password can be verified with the given hash, or `false` otherwise. */ public boolean verifyPassword(String password, String hash) { if (null == password) { return false; } try { return BCrypt.checkpw(password, hash); } catch (Exception e) { return false; } }
Example #8
Source File: CredentialTraversalDsl.java From tinkerpop with Apache License 2.0 | 5 votes |
/** * Creates or updates a user. */ public default GraphTraversal<S, Vertex> user(final String username, final String password) { return has(VERTEX_LABEL_USER, PROPERTY_USERNAME, username). fold(). coalesce(__.unfold(), __.addV(VERTEX_LABEL_USER).property(PROPERTY_USERNAME, username)). property(PROPERTY_PASSWORD, BCrypt.hashpw(password, BCrypt.gensalt(CredentialTraversalDsl.BCRYPT_ROUNDS))); }
Example #9
Source File: AppCrypto.java From actframework with Apache License 2.0 | 5 votes |
/** * Verify a password against given hash. * * Note this method uses {@link act.conf.AppConfigKey#SECRET confiured application secret} * * @param password the password to be verified. * @param hash the hash used to verify the password * @return `true` if the password can be verified with the given hash, or `false` otherwise. */ public boolean verifyPassword(char[] password, String hash) { if (null == password) { return false; } try { return BCrypt.checkpw(password, hash); } catch (Exception e) { return false; } }
Example #10
Source File: UserUpdate.java From elepy with Apache License 2.0 | 5 votes |
@Override public User handleUpdate(HttpContext context, ModelContext<User> modelContext, ObjectMapper objectMapper) throws Exception { Crud<User> crud = modelContext.getCrud(); User loggedInUser = context.loggedInUserOrThrow(); User userToUpdateBefore = crud.getById(context.recordId()).orElseThrow(() -> new ElepyException("No user found with this ID", 404)); User userToUpdateAfter = updatedObjectFromRequest(userToUpdateBefore, context.request(), objectMapper, modelContext.getSchema()); // You can only execute this if the updating user is yourself, or you can administrate users if (!userToUpdateAfter.equals(loggedInUser)) { context.requirePermissions("users.update"); } checkPermissionIntegrity(loggedInUser, userToUpdateAfter, userToUpdateBefore); validateUpdate(context, modelContext, userToUpdateBefore, userToUpdateAfter); //If password is empty, use the old password if (userToUpdateAfter.getPassword().isEmpty()) { userToUpdateAfter.setPassword(userToUpdateBefore.getPassword()); } //Encrypt password if changed if (!userToUpdateAfter.getPassword().equals(userToUpdateBefore.getPassword())) { userToUpdateAfter.setPassword(BCrypt.hashpw(userToUpdateAfter.getPassword(), BCrypt.gensalt())); } // Finalize update and respond crud.update(userToUpdateAfter); context.status(200); context.result(Message.of("The user has been updated", 200)); return userToUpdateAfter; }
Example #11
Source File: UserCenter.java From elepy with Apache License 2.0 | 5 votes |
public Optional<User> login(String usernameOrEmail, String password) { Optional<User> user = getUserByUsername(usernameOrEmail); if (user.isPresent() && BCrypt.checkpw(password, user.get().getPassword())) { return user; } return Optional.empty(); }
Example #12
Source File: BasicFunctionalityTest.java From elepy with Apache License 2.0 | 5 votes |
@Test void can_Login_and_UpdateOwnPassword_AsSuperUser() throws JsonProcessingException, UnirestException { createInitialUsersViaHttp(); final HttpResponse<String> authorizedFind = Unirest .patch(elepy + "/users" + "/[email protected]") .queryString("password", "newPassword") .basicAuth("[email protected]", "[email protected]") .asString(); final var admin = userCrud.getById("[email protected]").orElseThrow(); assertThat(authorizedFind.getStatus()).isEqualTo(200); assertThat(BCrypt.checkpw("newPassword", admin.getPassword())) .isTrue(); }
Example #13
Source File: Utils.java From para with Apache License 2.0 | 5 votes |
/** * Checks if a hash matches a string. * * @param plain plain text string * @param storedHash hashed string * @return true if the hash matches */ public static boolean bcryptMatches(String plain, String storedHash) { if (StringUtils.isBlank(plain) || StringUtils.isBlank(storedHash)) { return false; } try { return BCrypt.checkpw(plain, storedHash); } catch (Exception e) { return false; } }
Example #14
Source File: UserUtils.java From realworld-api-quarkus with MIT License | 5 votes |
public static User create(String username, String email, String userPassword) { User user = new User(); user.setUsername(username); user.setEmail(email); user.setPassword(BCrypt.hashpw(userPassword, BCrypt.gensalt())); return user; }
Example #15
Source File: PlayerPersistence.java From luna with MIT License | 5 votes |
/** * Synchronously saves persistent data. * * @param username The username of the player to save. * @param data The data to save. */ public void save(String username, PlayerData data) throws Exception { if (data.needsHash) { data.password = BCrypt.hashpw(data.plainTextPassword, BCrypt.gensalt()); } serializer.save(username, data); }
Example #16
Source File: CredentialTraversalSourceDsl.java From tinkerpop with Apache License 2.0 | 5 votes |
/** * Creates or updates a user. */ public GraphTraversal<Vertex, Vertex> user(final String username, final String password) { return this.clone().V(). has(VERTEX_LABEL_USER, PROPERTY_USERNAME, username). fold(). coalesce(__.unfold(), __.addV(VERTEX_LABEL_USER).property(PROPERTY_USERNAME, username)). property(PROPERTY_PASSWORD, BCrypt.hashpw(password, BCrypt.gensalt(CredentialTraversalDsl.BCRYPT_ROUNDS))); }
Example #17
Source File: LoginClient.java From luna with MIT License | 5 votes |
/** * Determines what the login response should be once the player's data is loaded. * * @param data The loaded data. * @param enteredPassword The entered password. */ public LoginResponse getLoginResponse(PlayerData data, String enteredPassword) { if (data == null) { return LoginResponse.NORMAL; } else if (!BCrypt.checkpw(enteredPassword, data.password)) { return LoginResponse.INVALID_CREDENTIALS; } else if (data.isBanned()) { return LoginResponse.ACCOUNT_BANNED; } else { return LoginResponse.NORMAL; } }
Example #18
Source File: UserController.java From javalin-website-example with Apache License 2.0 | 5 votes |
public static boolean authenticate(String username, String password) { if (username == null || password == null) { return false; } User user = userDao.getUserByUsername(username); if (user == null) { return false; } String hashedPassword = BCrypt.hashpw(password, user.salt); return hashedPassword.equals(user.hashedPassword); }
Example #19
Source File: UserController.java From javalin-website-example with Apache License 2.0 | 5 votes |
public static void setPassword(String username, String oldPassword, String newPassword) { if (authenticate(username, oldPassword)) { String newSalt = BCrypt.gensalt(); String newHashedPassword = BCrypt.hashpw(newSalt, newPassword); // Update the user salt and password } }
Example #20
Source File: PasswordEncoder.java From jersey-jwt with MIT License | 5 votes |
/** * Checks a password against a stored hash using BCrypt. * * @param plainTextPassword * @param hashedPassword * @return */ public boolean checkPassword(String plainTextPassword, String hashedPassword) { if (null == hashedPassword || !hashedPassword.startsWith("$2a$")) { throw new RuntimeException("Hashed password is invalid"); } return BCrypt.checkpw(plainTextPassword, hashedPassword); }
Example #21
Source File: DataGenerator.java From TeaStore with Apache License 2.0 | 5 votes |
private void generateUsers(int users) { IntStream.range(0, users).parallel().forEach(i -> { User user = new User(); user.setUserName("user" + i); user.setEmail("user" + i + "@teastore.com"); user.setRealName(FIRSTNAMES[random.nextInt(FIRSTNAMES.length)] + " " + LASTNAMES[random.nextInt(LASTNAMES.length)]); user.setPassword(BCrypt.hashpw(PASSWORD, BCrypt.gensalt(6))); UserRepository.REPOSITORY.createEntity(user); }); }
Example #22
Source File: CartTest.java From TeaStore with Apache License 2.0 | 5 votes |
private void mockUser1() { User u = new User(); u.setEmail("[email protected]"); u.setRealName("asdas asdasd"); u.setUserName("user1"); u.setPassword(BCrypt.hashpw("password", BCrypt.gensalt())); u.setId(1231245125); mockValidGetRestCall(u, "/tools.descartes.teastore.persistence/rest/users/name/user1"); }
Example #23
Source File: LoginLogoutTest.java From TeaStore with Apache License 2.0 | 5 votes |
private void mockUser1() { User u = new User(); u.setEmail("[email protected]"); u.setRealName("asdas asdasd"); u.setUserName("user1"); u.setPassword(BCrypt.hashpw("password", BCrypt.gensalt())); u.setId(1231245125); mockValidGetRestCall(u, "/tools.descartes.teastore.persistence/rest/users/name/user1"); }
Example #24
Source File: AuthController.java From tutorials with MIT License | 5 votes |
@Post("/register") public void register(User user, HttpServletRequest request) { validator.validate(user); if(validator.hasErrors()) { result.include("errors", validator.getErrors()); } validator.onErrorRedirectTo(this).registrationForm(); if(!user.getPassword() .equals(request.getParameter("password_confirmation"))) { result.include("error", "Passwords Do Not Match"); result.redirectTo(this).registrationForm(); } user.setPassword( BCrypt.hashpw(user.getPassword(), BCrypt.gensalt())); Object resp = userDao.add(user); if(resp != null) { result.include("status", "Registration Successful! Now Login"); result.redirectTo(this).loginForm(); } else { result.include("error", "There was an error during registration"); result.redirectTo(this).registrationForm(); } }
Example #25
Source File: UpdatableBCrypt.java From StubbornJava with MIT License | 5 votes |
public boolean verifyAndUpdateHash(String password, String hash, Function<String, Boolean> updateFunc) { if (BCrypt.checkpw(password, hash)) { int rounds = getRounds(hash); // It might be smart to only allow increasing the rounds. // If someone makes a mistake the ability to undo it would be nice though. if (rounds != logRounds) { log.debug("Updating password from {} rounds to {}", rounds, logRounds); String newHash = hash(password); return updateFunc.apply(newHash); } return true; } return false; }
Example #26
Source File: UserDAOTest.java From keywhiz with Apache License 2.0 | 5 votes |
@Before public void setUp() { userDAO = new UserDAO(jooqContext); hashedPassword = BCrypt.hashpw("password", BCrypt.gensalt()); jooqContext.insertInto(USERS, USERS.USERNAME, USERS.PASSWORD_HASH, USERS.CREATED_AT, USERS.UPDATED_AT) .values("user", hashedPassword, OffsetDateTime.now().toEpochSecond(), OffsetDateTime.now().toEpochSecond()) .execute(); }
Example #27
Source File: BcryptAuthenticator.java From keywhiz with Apache License 2.0 | 5 votes |
/** * Constant-time password check * @param password a password to be checked * @param hash a hash which may match the output of hashPassword for this password * @return whether the password matches the hash */ private static boolean checkPassword(String password, Optional<String> hash) { // We want to check the password in constant time, to avoid leaking information about whether // a user is present in the database. In order to do this we pass a fake bcrypt hash into the // checkpw function so we do the work of checking a hash even if there was no user present // in the database. We return true iff there was a user/hash present *and* hash was valid. String fakeHash = hashPassword(""); boolean valid = BCrypt.checkpw(password, hash.orElse(fakeHash)); return hash.isPresent() && valid; }
Example #28
Source File: UpdatableBCrypt.java From StubbornJava with MIT License | 5 votes |
public boolean verifyAndUpdateHash(String password, String hash, Function<String, Boolean> updateFunc) { if (BCrypt.checkpw(password, hash)) { int rounds = getRounds(hash); // It might be smart to only allow increasing the rounds. // If someone makes a mistake the ability to undo it would be nice though. if (rounds != logRounds) { log.debug("Updating password from {} rounds to {}", rounds, logRounds); String newHash = hash(password); return updateFunc.apply(newHash); } return true; } return false; }
Example #29
Source File: BCryptEncryptionModule.java From cuba with Apache License 2.0 | 5 votes |
@Override public boolean checkPassword(User user, String rawPassword) { if (user.getPassword() == null) { return false; } return BCrypt.checkpw(rawPassword, user.getPassword()); }
Example #30
Source File: BCryptProvider.java From gocd-filebased-authentication-plugin with Apache License 2.0 | 5 votes |
@Override public String hash(CliArguments arguments) { final String salt = BCrypt.gensalt(arguments.cost()); final String hashedPasswd = BCrypt.hashpw(arguments.password(), salt); return format("{0}={1}", arguments.username(), hashedPasswd); }