Java Examples for org.mindrot.jbcrypt.BCrypt
The following java examples will help you to understand the usage of org.mindrot.jbcrypt.BCrypt. These source code samples are taken from different open source projects.
Example 1
| Project: dependency-track-master File: DefaultObjectGenerator.java View source code |
/**
* Loads the default users into the database if no User data exists.
*/
@SuppressWarnings("unchecked")
public void loadDefaultUsers() {
final Session session = sessionFactory.openSession();
final int count = ((Long) session.createQuery("select count(*) from User ").uniqueResult()).intValue();
// Check to see if data already exists in the table.
if (count > 0) {
session.close();
return;
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Adding default users to datastore.");
}
session.beginTransaction();
final Query query = session.createQuery(" FROM Roles ");
final ArrayList<Roles> rolelist = (ArrayList<Roles>) query.list();
Roles adminRole = null;
for (Roles role : rolelist) {
if (role.getRole().equalsIgnoreCase(Roles.ROLE.ADMIN.name())) {
adminRole = role;
}
}
if (adminRole == null) {
return;
}
final String hashedPassword = BCrypt.hashpw("admin", BCrypt.gensalt(14));
final User user = new User();
user.setIsLdap(false);
user.setPassword(hashedPassword);
user.setUsername("admin");
user.setCheckvalid(false);
user.setRoles(adminRole);
session.save(user);
session.getTransaction().commit();
session.close();
}Example 2
| Project: ISP-ng-master File: AuthenticationMigrationAutomationIntegration.java View source code |
/**
* Checks password is present in LDAP, if not try to verify it using old password hash (bcrypt).
* If valid, set password in LDAP and proceed
*
* @param dn
* @param password
*/
public static int intercept(String dn, String password) {
Optional<String> pwdFile = Config.get("util/migration/passwordFile");
if (!pwdFile.isPresent()) {
return 0;
}
if (passwords.isEmpty()) {
try {
ObjectMapper om = new ObjectMapper();
HashMap<Object, Object> val = om.readValue(new File(pwdFile.get()), HashMap.class);
for (Map.Entry<Object, Object> entry : val.entrySet()) {
if (entry.getKey() instanceof String) {
passwords.put(entry.getKey().toString(), entry.getValue().toString());
}
}
} catch (Exception ex) {
Logger.getLogger(AuthenticationMigrationAutomationIntegration.class).error("Failed to load migration password file", ex);
}
}
String email = dn.substring(5, dn.indexOf(','));
User user = Users.get(email);
if (user != null) {
if (user.getPassword().equals("")) {
// Empty password found, check if old password exists, and if so, migrate
if (passwords.containsKey(email) && BCrypt.checkpw(password, passwords.get(email))) {
user.setPassword(password);
Users.update(user);
return 1;
} else {
Logger.getLogger(AuthenticationMigrationAutomationIntegration.class).error("User " + email + " has no password set");
}
} else {
return 0;
}
}
return -1;
}Example 3
| Project: justaddwater-master File: SignupPage.java View source code |
private void createAccount(User user, String username, String password) {
log.info("createAccount username: " + username);
user.setEmail(username);
String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
user.setPassword(hashed);
user.setAccountCreationDate(new Date());
user.setAuthenticationType(AuthenticationType.local);
em.persist(user);
action.apply();
session.setUsername(user.getEmail());
// elasticEmail.sendEmail("yourapp account created", "yourapp account created: " + user.getEmail(), SearchPage.CONTACT_EMAIL_ADDRESS);
}Example 4
| Project: keywhiz-master File: UserDAOTest.java View source code |
@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 5
| Project: saltedhashed-master File: VerifierTest.java View source code |
@Test
public void bcryptTest() {
String password = PasswordUtils.getRandomPassword();
String hash = BCrypt.hashpw(password, BCrypt.gensalt(5));
PasswordResponse response = new PasswordResponse();
response.setAlgorithm(Algorithm.BCRYPT);
response.setHash(hash);
Assert.assertTrue(verifier.verify(password, response));
Assert.assertFalse(verifier.verify(password + " ", response));
}Example 6
| Project: FlexibleLogin-master File: BcryptHasher.java View source code |
@Override
public boolean checkPassword(String passwordHash, String userInput) {
String checkedHash = passwordHash;
//from other implementations like in PHP
if (passwordHash.charAt(2) == 'y') {
//http://stackoverflow.com/questions/27418597/bcrypt-version-1-1-2y-for-java
//skip one position in order to ignore the 'y'
checkedHash = passwordHash.substring(0, 2) + 'a' + passwordHash.substring(3, passwordHash.length());
}
return BCrypt.checkpw(userInput, checkedHash);
}Example 7
| Project: jabox-master File: JaboxAuthenticatedWebSession.java View source code |
/**
* @see org.apache.wicket.authentication.AuthenticatedWebSession#authenticate(java.lang.String,
* java.lang.String)
*/
@Override
public boolean authenticate(final String username, final String password) {
if (username == null || password == null) {
return false;
}
User user = UserXstreamDao.getUser(username);
if (user == null) {
return false;
}
if (!username.equals(user.getLogin())) {
return false;
}
if (BCrypt.checkpw(password, user.getPasswordHash())) {
_username = user.getLogin();
return true;
} else {
return false;
}
}Example 8
| Project: restheart-master File: HashTransformer.java View source code |
/**
*
* @param exchange
* @param context
* @param contentToTransform
* @param args properties to filter out as an array of strings (["prop1",
* "prop2"]
*/
@Override
public void transform(final HttpServerExchange exchange, final RequestContext context, BsonValue contentToTransform, final BsonValue args) {
if (!doesApply(context) || contentToTransform == null) {
// nothing to do
return;
}
if (context.getType() == TYPE.DOCUMENT && (context.getMethod() == RequestContext.METHOD.PATCH || context.getMethod() == RequestContext.METHOD.PUT)) {
}
if (!contentToTransform.isDocument()) {
throw new IllegalStateException("content to transform is not a document");
}
BsonDocument _contentToTransform = contentToTransform.asDocument();
if (args.isDocument()) {
BsonValue _tohash = args.asDocument().get("props");
if (_tohash == null || !_tohash.isArray()) {
context.addWarning("transformer wrong definition: " + "args must be an object as {'props': [ 'password' ], " + "'complexity': 12 }");
}
BsonArray tohash = _tohash.asArray();
BsonValue _complexity = args.asDocument().get("complexity");
if (_complexity != null && !_complexity.isNumber()) {
context.addWarning("transformer wrong definition: " + "args must be an object as {'props': [ 'password' ], " + "'complexity': 12 }");
}
int complexity = _complexity == null ? 12 : _complexity.asNumber().intValue();
tohash.forEach( _prop -> {
if (_prop.isString()) {
String prop = (String) _prop.asString().getValue();
BsonValue _value = _contentToTransform.get(prop);
if (_value != null && _value.isString()) {
String value = _value.asString().getValue();
_contentToTransform.replace(prop, new BsonString(BCrypt.hashpw(value, BCrypt.gensalt(complexity))));
}
} else {
context.addWarning("property in the args list " + "is not a string: " + _prop);
}
});
} else {
context.addWarning("transformer wrong definition: " + "args must be an object as {'props': [ 'password'], " + "'complexity': 12 }");
}
}Example 9
| Project: divide-master File: AuthServerLogic.java View source code |
/*
* Saves user credentials
*/
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);
//decrypt the password
toSave.decryptPassword(keyManager.getPrivateKey());
String de = toSave.getPassword();
String ha = BCrypt.hashpw(de, BCrypt.gensalt(10));
toSave.setOwnerId(dao.count(Credentials.class.getName()) + 1);
//hash the password for storage
toSave.setPassword(ha);
toSave.setAuthToken(AuthTokenUtils.getNewToken(keyManager.getSymmetricKey(), toSave));
toSave.setRecoveryToken(AuthTokenUtils.getNewToken(keyManager.getSymmetricKey(), toSave));
dao.save(toSave);
return toSave;
}Example 10
| Project: restx-master File: HashShellCommand.java View source code |
@Override
public void run(RestxShell shell) throws Exception {
switch(hash) {
case "md5":
shell.println(Hashing.md5().hashString(plaintext, Charsets.UTF_8).toString());
break;
case "sha1":
shell.println(Hashing.sha1().hashString(plaintext, Charsets.UTF_8).toString());
break;
case "bcrypt":
shell.println(BCrypt.hashpw(plaintext, BCrypt.gensalt()));
break;
case "md5+bcrypt":
shell.println(BCrypt.hashpw(Hashing.md5().hashString(plaintext, Charsets.UTF_8).toString(), BCrypt.gensalt()));
break;
case "sha1+bcrypt":
shell.println(BCrypt.hashpw(Hashing.sha1().hashString(plaintext, Charsets.UTF_8).toString(), BCrypt.gensalt()));
break;
default:
shell.printIn("unknown hash function: " + hash, RestxShell.AnsiCodes.ANSI_RED);
shell.println("");
}
}Example 11
| Project: upsource-bot-master File: UserResource.java View source code |
@POST
@Path("/{id}")
public Response editUser(@FormParam("current") String currentPassword, @FormParam("password") String password, @FormParam("password-repeat") String passwordRepeat, @PathParam("id") long id) {
if (currentPassword == null || password == null || passwordRepeat == null) {
throw new BadRequestException();
}
User user = dao.findById(id);
if (user == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new UserView(null)).build();
}
boolean error = false;
boolean passwordIncorrect = false;
if (!BCrypt.checkpw(currentPassword, user.getPasswordHash())) {
error = true;
passwordIncorrect = true;
}
boolean passwordEmpty = false;
if (password.trim().isEmpty()) {
error = true;
passwordEmpty = true;
}
boolean passwordMismatch = false;
if (!password.equals(passwordRepeat)) {
error = true;
passwordMismatch = true;
}
if (!error) {
int rowsChanged = dao.updatePassword(BCrypt.hashpw(password, BCrypt.gensalt()), id);
if (rowsChanged == 0) {
return Response.status(Response.Status.NOT_FOUND).entity(new UserView(null)).build();
}
}
return Response.status(error ? Response.Status.BAD_REQUEST : Response.Status.OK).entity(new UserView(user, passwordMismatch, passwordEmpty, passwordIncorrect)).build();
}Example 12
| Project: user-master File: BcryptCommand.java View source code |
/* (non-Javadoc)
* @see org.apache.usergrid.security.crypto.command.EncryptionCommand#auth(byte[],
* org.apache.usergrid.persistence.CredentialsInfo, java.util.UUID, java.util.UUID)
*/
public byte[] auth(byte[] input, CredentialsInfo info, UUID userId, UUID applicationId) {
//our existing has the salt in it, extract it and re-use it
String infoSecret = info.getSecret();
Assert.notNull(infoSecret, "The credentials info must have a bcrypt compatible secret to perform auth");
String existing = new String(decodeBase64(infoSecret), UTF8);
return BCrypt.hashpw(new String(input, UTF8), existing).getBytes(UTF8);
}Example 13
| Project: usergrid-master File: BcryptCommand.java View source code |
/* (non-Javadoc)
* @see org.apache.usergrid.security.crypto.command.EncryptionCommand#auth(byte[],
* org.apache.usergrid.persistence.CredentialsInfo, java.util.UUID, java.util.UUID)
*/
public byte[] auth(byte[] input, CredentialsInfo info, UUID userId, UUID applicationId) {
//our existing has the salt in it, extract it and re-use it
String infoSecret = info.getSecret();
Assert.notNull(infoSecret, "The credentials info must have a bcrypt compatible secret to perform auth");
String existing = new String(decodeBase64(infoSecret), UTF8);
return BCrypt.hashpw(new String(input, UTF8), existing).getBytes(UTF8);
}Example 14
| Project: tinkerpop-master File: SimpleAuthenticator.java View source code |
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);
try {
user = credentialStore.findUser(username);
} catch (IllegalStateException ex) {
logger.warn(ex.getMessage());
throw new AuthenticationException("Username and/or password are incorrect", ex);
} catch (Exception ex) {
throw new AuthenticationException("Username and/or password are incorrect", ex);
}
if (null == user)
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 15
| Project: NemakiWare-master File: UserResource.java View source code |
@POST
@Path("/create/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String create(@PathParam("repositoryId") String repositoryId, @PathParam("id") String userId, @FormParam(FORM_USERNAME) String name, @FormParam(FORM_PASSWORD) String password, @FormParam(FORM_FIRSTNAME) String firstName, @FormParam(FORM_LASTNAME) String lastName, @FormParam(FORM_EMAIL) String email, @Context HttpServletRequest httpRequest) {
boolean status = true;
JSONObject result = new JSONObject();
JSONArray errMsg = new JSONArray();
// Validation
status = validateNewUser(status, errMsg, userId, name, firstName, lastName, password, repositoryId);
// Create a user
if (status) {
// initialize mandatory but space-allowed parameters
if (StringUtils.isBlank(lastName))
lastName = "";
if (StringUtils.isBlank(email))
email = "";
// Generate a password hash
String passwordHash = BCrypt.hashpw(password, BCrypt.gensalt());
User user = new User(userId, name, firstName, lastName, email, passwordHash);
setFirstSignature(httpRequest, user);
// TODO Error handling
principalService.createUser(repositoryId, user);
}
result = makeResult(status, result, errMsg);
return result.toJSONString();
}Example 16
| Project: OpenLegislation-master File: AdminAccountCtrl.java View source code |
/**
* Change Password API
* -------------------
*
* Changes the password for the calling user.
*
* (POST) /api/3/admin/accounts/passchange
*
* Request params: password (string) - The new password
*
* Expected Output: successful pass-changed response if the password was changed, ErrorResponse otherwise
*/
@RequiresPermissions("admin")
@RequestMapping(value = "/passchange", method = RequestMethod.POST)
public Object changePassword(@RequestParam(required = true) String password) {
String username = getSubjectUsername();
AdminUser user = adminUserService.getAdminUser(username);
if (BCrypt.checkpw(password, user.getPassword())) {
return new ResponseEntity<>(new ErrorResponse(ErrorCode.SAME_PASSWORD), HttpStatus.BAD_REQUEST);
}
if (password.length() < minPassLength) {
throw new InvalidRequestParamEx(password.replaceAll(".", "*"), "password", "String", "Password must contain at least " + minPassLength + " characters");
}
user.setPassword(password);
adminUserService.createUser(user);
return new SimpleResponse(true, "Password has been successfully changed", "pass-changed");
}Example 17
| Project: rce-master File: InstanceManagementServiceImpl.java View source code |
/**
* The IM master uses the same passphrase for all instances. This method retreives the passphrase from the persistent settings. If no
* passphrase is stored yet, it is created randomly.
*
* @return the password hash
*/
private String getHashedPassphrase() {
String passphrase = persistentSettingsService.readStringValue(InstanceManagementConstants.IM_MASTER_PASSPHRASE_KEY);
if (passphrase == null) {
passphrase = RandomStringUtils.randomAlphanumeric(10);
persistentSettingsService.saveStringValue(InstanceManagementConstants.IM_MASTER_PASSPHRASE_KEY, passphrase);
}
return BCrypt.hashpw(passphrase, BCrypt.gensalt(10));
}Example 18
| Project: scylla-tools-java-master File: PasswordAuthenticator.java View source code |
private AuthenticatedUser doAuthenticate(String username, String password, SelectStatement authenticationStatement) throws RequestExecutionException, AuthenticationException {
ResultMessage.Rows rows = authenticationStatement.execute(QueryState.forInternalCalls(), QueryOptions.forInternalCalls(consistencyForRole(username), Lists.newArrayList(ByteBufferUtil.bytes(username))));
UntypedResultSet result = UntypedResultSet.create(rows.result);
if ((result.isEmpty() || !result.one().has(SALTED_HASH)) || !BCrypt.checkpw(password, result.one().getString(SALTED_HASH)))
throw new AuthenticationException("Username and/or password are incorrect");
return new AuthenticatedUser(username);
}Example 19
| Project: syncthing-android-master File: ConfigXml.java View source code |
/**
* Generates username and config, stores them in config and preferences.
*
* We have to store the plaintext password in preferences, because we need it in
* WebGuiActivity. The password in the config is hashed, so we can't use it directly.
*/
private void generateLoginInfo() {
char[] chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
StringBuilder password = new StringBuilder();
SecureRandom random = new SecureRandom();
for (int i = 0; i < 20; i++) password.append(chars[random.nextInt(chars.length)]);
String user = Build.MODEL.replaceAll("[^a-zA-Z0-9 ]", "");
Log.i(TAG, "Generated GUI username and password (username is " + user + ")");
Node userNode = mConfig.createElement("user");
getGuiElement().appendChild(userNode);
userNode.setTextContent(user);
Node passwordNode = mConfig.createElement("password");
getGuiElement().appendChild(passwordNode);
String hashed = BCrypt.hashpw(password.toString(), BCrypt.gensalt());
passwordNode.setTextContent(hashed);
PreferenceManager.getDefaultSharedPreferences(mContext).edit().putString("web_gui_password", password.toString()).apply();
}Example 20
| Project: ACaZoo-master File: PasswordAuthenticator.java View source code |
public AuthenticatedUser authenticate(Map<String, String> credentials) throws AuthenticationException {
String username = credentials.get(USERNAME_KEY);
if (username == null)
throw new AuthenticationException(String.format("Required key '%s' is missing", USERNAME_KEY));
String password = credentials.get(PASSWORD_KEY);
if (password == null)
throw new AuthenticationException(String.format("Required key '%s' is missing", PASSWORD_KEY));
UntypedResultSet result;
try {
ResultMessage.Rows rows = authenticateStatement.execute(QueryState.forInternalCalls(), new QueryOptions(consistencyForUser(username), Lists.newArrayList(ByteBufferUtil.bytes(username))));
result = new UntypedResultSet(rows.result);
} catch (RequestValidationException e) {
throw new AssertionError(e);
} catch (RequestExecutionException e) {
throw new AuthenticationException(e.toString());
}
if (result.isEmpty() || !BCrypt.checkpw(password, result.one().getString(SALTED_HASH)))
throw new AuthenticationException("Username and/or password are incorrect");
return new AuthenticatedUser(username);
}Example 21
| Project: cassandra-cqlMod-master File: PasswordAuthenticator.java View source code |
public AuthenticatedUser authenticate(Map<String, String> credentials) throws AuthenticationException {
String username = credentials.get(USERNAME_KEY);
if (username == null)
throw new AuthenticationException(String.format("Required key '%s' is missing", USERNAME_KEY));
String password = credentials.get(PASSWORD_KEY);
if (password == null)
throw new AuthenticationException(String.format("Required key '%s' is missing", PASSWORD_KEY));
UntypedResultSet result;
try {
ResultMessage.Rows rows = authenticateStatement.execute(QueryState.forInternalCalls(), new QueryOptions(consistencyForUser(username), Lists.newArrayList(ByteBufferUtil.bytes(username))));
result = UntypedResultSet.create(rows.result);
} catch (RequestValidationException e) {
throw new AssertionError(e);
} catch (RequestExecutionException e) {
throw new AuthenticationException(e.toString());
}
if (result.isEmpty() || !BCrypt.checkpw(password, result.one().getString(SALTED_HASH)))
throw new AuthenticationException("Username and/or password are incorrect");
return new AuthenticatedUser(username);
}Example 22
| Project: CassandraQoS-master File: PasswordAuthenticator.java View source code |
public AuthenticatedUser authenticate(Map<String, String> credentials) throws AuthenticationException {
String username = credentials.get(USERNAME_KEY);
if (username == null)
throw new AuthenticationException(String.format("Required key '%s' is missing", USERNAME_KEY));
String password = credentials.get(PASSWORD_KEY);
if (password == null)
throw new AuthenticationException(String.format("Required key '%s' is missing", PASSWORD_KEY));
UntypedResultSet result;
try {
ResultMessage.Rows rows = authenticateStatement.execute(QueryState.forInternalCalls(), new QueryOptions(consistencyForUser(username), Lists.newArrayList(ByteBufferUtil.bytes(username))));
result = new UntypedResultSet(rows.result);
} catch (RequestValidationException e) {
throw new AssertionError(e);
} catch (RequestExecutionException e) {
throw new AuthenticationException(e.toString());
}
if (result.isEmpty() || !BCrypt.checkpw(password, result.one().getString(SALTED_HASH)))
throw new AuthenticationException("Username and/or password are incorrect");
return new AuthenticatedUser(username);
}Example 23
| Project: stratio-cassandra-master File: PasswordAuthenticator.java View source code |
public AuthenticatedUser authenticate(Map<String, String> credentials) throws AuthenticationException {
String username = credentials.get(USERNAME_KEY);
if (username == null)
throw new AuthenticationException(String.format("Required key '%s' is missing", USERNAME_KEY));
String password = credentials.get(PASSWORD_KEY);
if (password == null)
throw new AuthenticationException(String.format("Required key '%s' is missing", PASSWORD_KEY));
UntypedResultSet result;
try {
ResultMessage.Rows rows = authenticateStatement.execute(QueryState.forInternalCalls(), QueryOptions.forInternalCalls(consistencyForUser(username), Lists.newArrayList(ByteBufferUtil.bytes(username))));
result = UntypedResultSet.create(rows.result);
} catch (RequestValidationException e) {
throw new AssertionError(e);
} catch (RequestExecutionException e) {
throw new AuthenticationException(e.toString());
}
if (result.isEmpty() || !BCrypt.checkpw(password, result.one().getString(SALTED_HASH)))
throw new AuthenticationException("Username and/or password are incorrect");
return new AuthenticatedUser(username);
}Example 24
| Project: MoparScape-master File: JdbcSerializer.java View source code |
@Override
public SerializeResult loadPlayer(String username, String password) {
try {
loginStatement.setString(1, username);
try (ResultSet set = loginStatement.executeQuery()) {
if (set.first()) {
int id = set.getInt("id");
String hashedPassword = set.getString("password");
if (BCrypt.checkpw(password, hashedPassword)) {
Player player = new Player();
player.setDatabaseId(id);
player.setPassword(password);
/* can't use hashed one in PlayerTable */
for (Table<Player> table : playerTables) table.load(player);
return new SerializeResult(LoginResponse.STATUS_OK, player);
}
}
return new SerializeResult(LoginResponse.STATUS_INVALID_PASSWORD);
}
} catch (SQLExceptionIOException | ex) {
logger.warn("Loading player " + username + " failed.", ex);
return new SerializeResult(LoginResponse.STATUS_COULD_NOT_COMPLETE);
}
}Example 25
| Project: CommandHelper-master File: Crypto.java View source code |
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
int log_rounds = 5;
if (args.length == 2) {
log_rounds = Static.getInt32(args[1], t);
}
try {
String hash = BCrypt.hashpw(args[0].val(), BCrypt.gensalt(log_rounds));
return new CString(hash, t);
} catch (IllegalArgumentException ex) {
throw new CRERangeException(ex.getMessage(), t);
}
}Example 26
| Project: secrets-for-android-master File: SecurityUtils.java View source code |
/**
* Create a decryption cipher using an old algorithm based on the given
* password string. The string is not stored internally.
*
* This method is used for backward compatibility only.
*
* @param password String to use for creating the ciphers.
* @param salt The salt to use when creating the encryption key.
* @param rounds The number of rounds for bcrypt.
* @return True if the ciphers were successfully created.
*/
public static Cipher createDecryptionCipherV2(String password, byte[] salt, int rounds) {
if (salt == null || rounds == 0)
return null;
Cipher cipher = null;
try {
int plaintext[] = { 0x155cbf8e, 0x57f57513, 0x3da787b9, 0x71679d82, 0x7cf72e93, 0x1ae25274, 0x64b54adc, 0x335cbd0b };
BCrypt bcrypt = new BCrypt();
byte[] rawBytes = bcrypt.crypt_raw(password.getBytes("UTF-8"), salt, rounds, plaintext);
SecretKeySpec spec = new SecretKeySpec(rawBytes, KEY_FACTORY_V2);
// For backwards compatibility with secrets create on Android M and
// earlier, create an initial vector of all zeros.
IvParameterSpec params = new IvParameterSpec(new byte[16]);
cipher = Cipher.getInstance(CIPHER_FACTORY_V2);
cipher.init(Cipher.DECRYPT_MODE, spec, params);
} catch (Exception ex) {
Log.d(LOG_TAG, "createCiphersV2", ex);
}
return cipher;
}Example 27
| Project: TechnologyReadinessTool-master File: UserServiceImpl.java View source code |
@Override
@WebMethod(exclude = true)
@CoreDataModificationStatus(modificationType = ModificationType.UPDATE, entityClass = UserDO.class)
public void changePassword(ServiceContext context, String username, String password, String confirmPassword) {
List<ValidationError> errors = new ArrayList<>();
if (password == null || password.isEmpty() || password.length() < 8) {
String errorMessage = messageSource.getMessage("validation.user.password.minLength", null, null);
errors.add(new ValidationError("passwordField", "passwordField", errorMessage, "validation.user.password.minLength", errorMessage));
}
if (!confirmPassword.equals(password)) {
String errorMessage = messageSource.getMessage("validation.user.password.notMatch", null, null);
errors.add(new ValidationError("confirmPasswordField", "confirmPasswordField", errorMessage, "validation.user.password.notMatch", errorMessage));
}
User user = getByUsername(context, username);
ScopeExtDO complexitySEDO = scopeExtDAO.getLowestExistingConfigurationItem(user.getScope().getScopeId(), PASSWORD_COMPLEXITY);
if (complexitySEDO == null) {
// default to complexity of 3 if none found
complexitySEDO = new ScopeExtDO();
complexitySEDO.setValue("3");
}
int complexity = PasswordComplexityEvaluator.getPasswordComplexity(password);
int configuredComplexity = 0;
if (StringUtils.isNotBlank(complexitySEDO.getValue())) {
configuredComplexity = Integer.valueOf(complexitySEDO.getValue());
}
if (complexity < configuredComplexity) {
String errorMessage = messageSource.getMessage("validation.user.password.complexity", null, null);
errors.add(new ValidationError("passwordField", "passwordField", errorMessage, "validation.user.password.complexity", errorMessage));
}
if (!errors.isEmpty()) {
FaultInfo faultInfo = new FaultInfo();
faultInfo.setMessage("User failed validation.");
faultInfo.setAttributeErrors(errors);
throw new ValidationServiceException(faultInfo);
}
userDAO.changePassword(username, BCrypt.hashpw(password, BCrypt.gensalt()));
}Example 28
| Project: minitwit-master File: PasswordUtil.java View source code |
public static String hashPassword(String pwd) {
String hashed = BCrypt.hashpw(pwd, BCrypt.gensalt());
return hashed;
}Example 29
| Project: dropwizard-experiment-master File: HashedValue.java View source code |
/**
* Returns whether this is equal to the specified plaintext value.
* @param plaintext The plaintext.
*/
public boolean equalsPlaintext(String plaintext) {
return BCrypt.checkpw(plaintext, hashedValue);
}Example 30
| Project: mayocat-shop-master File: BCryptPasswordManager.java View source code |
public String hashPassword(String password) {
return BCrypt.hashpw(password, BCrypt.gensalt(configuration.getPasswordSaltLogRounds()));
}Example 31
| Project: eloquentia-master File: BcryptPasswordService.java View source code |
public String encryptPassword(Object plaintextPassword) throws IllegalArgumentException {
return BCrypt.hashpw(plaintextPassword.toString(), BCrypt.gensalt(10));
}Example 32
| Project: GWTP-Samples-master File: BCryptPasswordSecurity.java View source code |
@Override
public Boolean check(String password, String hashPassword) {
return BCrypt.checkpw(password, hashPassword);
}Example 33
| Project: isis-module-security-master File: PasswordEncryptionServiceUsingJBcryptTest.java View source code |
@Override
protected PasswordEncryptionService newPasswordEncryptionServiceDifferentSalt() {
final PasswordEncryptionServiceUsingJBcrypt service = new PasswordEncryptionServiceUsingJBcrypt();
// a different salt
service.salt = BCrypt.gensalt(12);
return service;
}Example 34
| Project: PlayStartApp-master File: Hash.java View source code |
/**
* Create an encrypted password from a clear string.
*
* @param clearString the clear string
* @return an encrypted password of the clear string
* @throws AppException APP Exception, from NoSuchAlgorithmException
*/
public static String createPassword(String clearString) throws AppException {
if (clearString == null) {
throw new AppException("No password defined!");
}
return BCrypt.hashpw(clearString, BCrypt.gensalt());
}Example 35
| Project: AugumentedSzczecin_java-master File: BasicAuthenticator.java View source code |
public static String generateSafeHash(final String plaintextPassword) {
return BCrypt.hashpw(plaintextPassword, BCrypt.gensalt(PW_HASH_SECURITY_LEVEL));
}Example 36
| Project: billing-ng-master File: BcryptProfile.java View source code |
@Override
public byte[] digest(String plainText) {
String hash = BCrypt.hashpw(plainText, BCrypt.gensalt(getWorkFactor()));
return hash.getBytes();
}Example 37
| Project: cloudname-master File: Password.java View source code |
public static String hashSecret(String secret) {
return BCrypt.hashpw(secret, BCrypt.gensalt(BCRYPT_LOG_ROUNDS));
}Example 38
| Project: femr-master File: BCryptPasswordEncryptor.java View source code |
@Override
public String encryptPassword(String password, int workFactor) {
String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt(workFactor));
return hashedPassword;
}Example 39
| Project: play-authenticate-master File: UsernamePasswordAuthUser.java View source code |
/**
* You *SHOULD* provide your own implementation of this which implements your own security.
*/
protected String createPassword(final String clearString) {
return BCrypt.hashpw(clearString, BCrypt.gensalt());
}Example 40
| Project: vector_health-master File: UsernamePasswordAuthUser.java View source code |
/**
* You *SHOULD* provide your own implementation of this which implements your own security.
*/
protected String createPassword(final String clearString) {
return BCrypt.hashpw(clearString, BCrypt.gensalt());
}Example 41
| Project: dataverse-master File: PasswordEncryption.java View source code |
@Override
public String encrypt(String plainText) {
return BCrypt.hashpw(plainText, BCrypt.gensalt());
}Example 42
| Project: graylog2-server-master File: BCryptPasswordAlgorithm.java View source code |
private String hash(String password, String salt) {
return PREFIX + BCrypt.hashpw(password, salt) + SALT_PREFIX + salt;
}Example 43
| Project: actframework-master File: AppCrypto.java View source code |
/**
* Generate crypted hash of given password. This method is more secure than
* {@link #passwordHash(String)} as it will fill the password char array
* with `\0` once used.
*
* See <a href="http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords-in-java">This SO for more detail</a>
* @param password the password
* @return the password hash
*/
public String passwordHash(char[] password) {
return BCrypt.hashpw(password, BCrypt.gensalt());
}Example 44
| Project: encrypted-camera-master File: AppPreferenceManager.java View source code |
/** * Stores the password as a hash. Using BCrypt! * * @param password the password to store */ public void setPassword(@NonNull String password) { // opting for speed here String hashed = BCrypt.hashpw(password, BCrypt.gensalt(4)); sharedPreferenceService.saveString(PASSWORD_HASH, hashed); }
Example 45
| Project: hot-reload-master File: AppCrypto.java View source code |
/**
* Generate crypted hash of given password. This method is more secure than
* {@link #passwordHash(String)} as it will fill the password char array
* with `\0` once used.
*
* See <a href="http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords-in-java">This SO for more detail</a>
* @param password the password
* @return the password hash
*/
public String passwordHash(char[] password) {
return BCrypt.hashpw(password, BCrypt.gensalt());
}Example 46
| Project: mangooio-master File: CodecUtils.java View source code |
/**
* Hashes a given cleartext data with JBCrypt
*
* @param data The cleartext data
* @return JBCrypted hashed value
*/
public static String hexJBcrypt(String data) {
Objects.requireNonNull(data, Required.DATA.toString());
return BCrypt.hashpw(data, BCrypt.gensalt(Default.JBCRYPT_ROUNDS.toInt()));
}Example 47
| Project: trilead-ssh2-master File: OpenSshCertificateDecoder.java View source code |
private static byte[] generateKayAndIvPbkdf2(byte[] password, byte[] salt, int rounds, int keyLength, int ivLength) {
byte[] keyAndIV = new byte[keyLength + ivLength];
new BCrypt().pbkdf(password, salt, rounds, keyAndIV);
return keyAndIV;
}Example 48
| Project: bergamot-master File: Contact.java View source code |
public void hashPassword(String plainPassword) {
this.passwordHash = BCrypt.hashpw(plainPassword, BCrypt.gensalt(BCRYPT_WORK_FACTOR));
// reset as we've updated the password
this.forcePasswordChange = false;
}Example 49
| Project: cassa-master File: PasswordAuthenticator.java View source code |
private AuthenticatedUser authenticate(String username, String password) throws AuthenticationException {
String hash = cache.get(username);
if (!BCrypt.checkpw(password, hash))
throw new AuthenticationException(String.format("Provided username %s and/or password are incorrect", username));
return new AuthenticatedUser(username);
}Example 50
| Project: cassandra-master File: PasswordAuthenticator.java View source code |
private AuthenticatedUser authenticate(String username, String password) throws AuthenticationException {
String hash = cache.get(username);
if (!BCrypt.checkpw(password, hash))
throw new AuthenticationException(String.format("Provided username %s and/or password are incorrect", username));
return new AuthenticatedUser(username);
}Example 51
| Project: aerospike-client-java-master File: AdminCommand.java View source code |
public static String hashPassword(String password) {
return BCrypt.hashpw(password, "$2a$10$7EqJtq98hPqEX7fNZaFWoO");
}Example 52
| Project: Magnolia-master File: SecurityUtil.java View source code |
public static String getBCrypt(String text) {
// gensalt's log_rounds parameter determines the complexity
// the work factor is 2^log_rounds, and the default is 10
String hashed = BCrypt.hashpw(text, BCrypt.gensalt(12));
return hashed;
}Example 53
| Project: jenkins-master File: HudsonPrivateSecurityRealm.java View source code |
public String encodePassword(String rawPass, Object _) throws DataAccessException {
return BCrypt.hashpw(rawPass, BCrypt.gensalt());
}Example 54
| Project: para-master File: Utils.java View source code |
/**
* bcrypt hash function implemented by Spring Security.
*
* @param s the string to be hashed
* @return the hash
*/
public static String bcrypt(String s) {
return (s == null) ? s : BCrypt.hashpw(s, BCrypt.gensalt(12));
}