List of usage examples for org.springframework.security.crypto.bcrypt BCrypt hashpw
public static String hashpw(byte passwordb[], String salt)
From source file:com.cfitzarl.cfjwed.data.model.Account.java
public void setPassword(String clearText) { password = BCrypt.hashpw(clearText, BCrypt.gensalt()); }
From source file:org.openbaton.nfvo.security.authentication.CustomUserDetailsService.java
@Override public void run(String... args) throws Exception { log.debug("Creating initial Users..."); if (!inMemManager.userExists("admin")) { UserDetails admin = new org.springframework.security.core.userdetails.User("admin", BCrypt.hashpw(adminPwd, BCrypt.gensalt(12)), true, true, true, true, AuthorityUtils.createAuthorityList("ADMIN")); inMemManager.createUser(admin);/*from w ww . j a v a 2s . c om*/ } else { log.debug("Admin" + inMemManager.loadUserByUsername("admin")); } for (User user : userRepository.findAll()) { if (!user.getUsername().equals("admin") && !user.getUsername().equals("guest")) { UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), true, true, true, true, AuthorityUtils.createAuthorityList("USER")); inMemManager.createUser(userDetails); } } log.debug("Users in UserDetailManager: "); log.info("ADMIN: " + inMemManager.loadUserByUsername("admin")); }
From source file:edu.jhuapl.openessence.security.OEPasswordEncoder.java
/** * * @param rawPass/*from w ww.j ava2 s . c o m*/ * @param encryptDetails an {@link EncryptionDetails} object * @return The encrypted version of the password * @throws DataAccessException */ @Override public String encodePassword(String rawPass, Object encryptDetails) throws DataAccessException { if ((encryptDetails == null) || !(encryptDetails.getClass().equals(EncryptionDetails.class))) { return ""; } String encPass = ""; String salt = ((EncryptionDetails) encryptDetails).getSalt(); String algorithm = ((EncryptionDetails) encryptDetails).getAlgorithm(); if (algorithm.equals("SHA-1")) { log.warn("SHA-1 DEPRECATED, retained for compatibility."); encPass = DigestUtils.sha1Hex(salt + rawPass); } else if (algorithm.equals("SHA-256")) { log.warn("SHA-256 DEPRECATED, retained for compatibility."); encPass = DigestUtils.sha256Hex(salt + rawPass); } else if (algorithm.equals("SHA-384")) { log.warn("SHA-384 DEPRECATED, retained for compatibility."); encPass = DigestUtils.sha384Hex(salt + rawPass); } else if (algorithm.equals("SHA-512")) { log.warn("SHA-512 DEPRECATED, retained for compatibility."); encPass = DigestUtils.sha512Hex(salt + rawPass); } else if (algorithm.equals("BCrypt")) { encPass = BCrypt.hashpw(rawPass, salt); } return encPass; }
From source file:org.jutge.joc.porra.security.MongoDBAuthenticationProvider.java
@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;/*from w w w . j a v a2 s .c o m*/ } // 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); }
From source file:org.jutge.joc.porra.service.AccountService.java
/** * Assume password has been set as plain text * @param account//from w w w .j av a 2 s. c om */ 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); }
From source file:org.biokoframework.system.services.crypto.impl.ProdEntityEncryptionService.java
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 {//ww w . j a va 2 s . c o m 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; }
From source file:bean.RedSocial.java
/** * //from w ww .jav a 2 s . co m * @param _username * @param _email * @param _password */ @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.ComentariosViaException.class) public void solicitarAcceso(String _username, String _email, String _password) { if (daoUsuario.obtenerUsuario(_username) != null) { throw new exceptionsBusiness.UsernameNoDisponible(); } String hash = BCrypt.hashpw(_password, BCrypt.gensalt()); Token token = new Token(_username, _email, hash); daoToken.guardarToken(token); //enviar token de acceso a la direccion email String correoEnvia = "skala2climbing@gmail.com"; String claveCorreo = "vNspLa5H"; // La configuracin para enviar correo Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); properties.put("mail.user", correoEnvia); properties.put("mail.password", claveCorreo); // Obtener la sesion Session session = Session.getInstance(properties, null); try { // Crear el cuerpo del mensaje MimeMessage mimeMessage = new MimeMessage(session); // Agregar quien enva el correo mimeMessage.setFrom(new InternetAddress(correoEnvia, "Skala2Climbing")); // Los destinatarios InternetAddress[] internetAddresses = { new InternetAddress(token.getEmail()) }; // Agregar los destinatarios al mensaje mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses); // Agregar el asunto al correo mimeMessage.setSubject("Confirmacin de registro"); // Creo la parte del mensaje MimeBodyPart mimeBodyPart = new MimeBodyPart(); String ip = "90.165.24.228"; mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: http://" + ip + ":8383/redsocialcolaborativaclientangularjs/confirmacion.html?" + "token=" + token.getToken()); //mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: "+"Enlace an no disponible"); // Crear el multipart para agregar la parte del mensaje anterior Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); // Agregar el multipart al cuerpo del mensaje mimeMessage.setContent(multipart); // Enviar el mensaje Transport transport = session.getTransport("smtp"); transport.connect(correoEnvia, claveCorreo); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } catch (UnsupportedEncodingException | MessagingException ex) { throw new ErrorEnvioEmail(); } }
From source file:org.mla.cbox.shibboleth.idp.authn.impl.ValidateUsernamePasswordAgainstMlaRest.java
/** {@inheritDoc} */ @Override/*from www. j a v a 2 s .com*/ protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext, @Nonnull final AuthenticationContext authenticationContext) { log.debug("{} Attempting to authenticate user {}", getLogPrefix(), getUsernamePasswordContext().getUsername()); try { // Construct the URL composed of the API root, members method with id value equal // to the username entered in the login form, the API key, and time stamp. StringBuilder urlBuilder = new StringBuilder().append(this.apiRoot).append("members/") .append(getUsernamePasswordContext().getUsername()).append("?").append("key=") .append(this.apiKey).append("×tamp=") .append(String.valueOf(Instant.now().getEpochSecond())); // The signature is created by prepending the GET method with a '&' separator to the // URL and then computing the SHA256 HMAC hash using the key. // StringBuilder baseStringBuilder = new StringBuilder().append("GET").append("&") .append(UriUtils.encode(urlBuilder.toString(), "UTF-8")); Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKey = new SecretKeySpec(this.apiSecret.getBytes("UTF-8"), "HmacSHA256"); sha256_HMAC.init(secretKey); String signature = Hex .encodeHexString(sha256_HMAC.doFinal(baseStringBuilder.toString().getBytes("UTF-8"))); // Append the signature to the URL. urlBuilder.append("&signature=").append(signature); log.debug("{} MLA query URL is {}", getLogPrefix(), urlBuilder.toString()); // Query the MLA API HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) { /* Set default parser as a JSON parser to make casting to class instance easier */ request.setParser(new JsonObjectParser(JSON_FACTORY)); } }); HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(urlBuilder.toString())); HttpResponse response = request.execute(); // Parse the response and create an instance of the MLAMemberObject. MLAMemberObject mlaMembership = response.parseAs(MLAMemberObject.class); List<MLAMemberObjectData> data = mlaMembership.getData(); // The data element, if present, is a list. If not present then the size of the list // is zero and this indicates that the username could not be found. if (data.size() < 1) { log.info("{} User {} is not known to MLA", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } // Parse out the id, username, password hash, and membership status. String memberId = data.get(0).getId(); String username = data.get(0).getAuthentication().getUsername(); String passwordHash = data.get(0).getAuthentication().getPassword(); String membershipStatus = data.get(0).getAuthentication().getMembership_status(); log.debug("{} MLA returned member Id {}", getLogPrefix(), memberId); log.debug("{} MLA returned username {}", getLogPrefix(), username); log.debug("{} MLA returned password hash {}", getLogPrefix(), passwordHash); log.debug("{} MLA returned membership status {}", getLogPrefix(), membershipStatus); // Non-active members cannot authenticate. if (!new String("active").equals(membershipStatus)) { log.info("{} User {} does not have active status", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } // Compute the bcrypt hash of the password using the salt sent by the MLA API. String pw_hash = BCrypt.hashpw(getUsernamePasswordContext().getPassword(), passwordHash); log.debug("{} Computed hash {}", getLogPrefix(), pw_hash); // Compare the input username with the password hash returned by the MLA API. if (!pw_hash.equals(passwordHash)) { log.info("{} Invalid password", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.INVALID_CREDENTIALS, AuthnEventIds.INVALID_CREDENTIALS); return; } // Set the username in the context directly because the user may have typed the member number // into the form rather than the username. The member number will work for authentication, // but we always want to return the username as the principal. getUsernamePasswordContext().setUsername(username); // Build the authentication result and proceed. log.info("{} Login by '{}' succeeded", getLogPrefix(), getUsernamePasswordContext().getUsername()); buildAuthenticationResult(profileRequestContext, authenticationContext); ActionSupport.buildProceedEvent(profileRequestContext); // } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | InterruptedException e) { } catch (IOException | NoSuchAlgorithmException | InvalidKeyException e) { log.warn("{} Login by {} produced exception", getLogPrefix(), getUsernamePasswordContext().getUsername(), e); handleError(profileRequestContext, authenticationContext, e, AuthnEventIds.AUTHN_EXCEPTION); } }
From source file:bean.RedSocial.java
/** * /* w w w . j a va 2 s . c o m*/ * @param _newPassword * @throws java.security.NoSuchAlgorithmException */ @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.CambiarPasswordException.class) public void cambiarPassword(String _newPassword) throws NoSuchAlgorithmException { String hash = BCrypt.hashpw(_newPassword, BCrypt.gensalt()); usuarioConectado = daoUsuario.obtenerUsuario(username); usuarioConectado.setPassword(hash); daoUsuario.actualizarUsuario(usuarioConectado); }