Example usage for org.springframework.security.crypto.bcrypt BCryptPasswordEncoder BCryptPasswordEncoder

List of usage examples for org.springframework.security.crypto.bcrypt BCryptPasswordEncoder BCryptPasswordEncoder

Introduction

In this page you can find the example usage for org.springframework.security.crypto.bcrypt BCryptPasswordEncoder BCryptPasswordEncoder.

Prototype

public BCryptPasswordEncoder() 

Source Link

Usage

From source file:cz.zcu.kiv.eegdatabase.wui.core.person.PersonServiceImpl.java

@Override
@Transactional/*from w ww .  ja v  a2 s. c o m*/
public void forgottenPassword(Person person) {

    String plainPassword = ControllerUtils.getRandomPassword();

    if (mailService.sendForgottenPasswordMail(person.getUsername(), plainPassword)) {
        log.debug("Updating new password into database");
        person.setPassword(new BCryptPasswordEncoder().encode(plainPassword));
        personDAO.update(person);
        log.debug("Password updated");
    } else {
        log.debug("E-mail message was NOT sent");
        log.debug("Password was NOT changed");
    }

}

From source file:com.cristian.tareask.controller.ProfileController.java

@RequestMapping(value = "/editprofile", method = RequestMethod.POST)
public String editProfile(HttpSession session, @RequestParam(value = "name") String name,
        @RequestParam(value = "subname") String subname, @RequestParam(value = "birthdate") String birthdate,
        @RequestParam(value = "phone") String phone, @RequestParam(value = "oldpassword") String oldpassword,
        @RequestParam(value = "newpassword") String newpassword, final RedirectAttributes redirectAttrs)
        throws ParseException {

    if ((session.getAttribute("namesession")) != null) {

        User u = new User();

        u = userService.getUserByName(session.getAttribute("namesession").toString());
        if (name == null || subname == null || birthdate == null || phone == null) {
            redirectAttrs.addFlashAttribute("editprofile", "Ups!. Unable to to update information.");
            return "redirect:profile.html";
        }/*from   w w w .  ja va2 s . c  o m*/

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = formatter.parse(birthdate);
        u.setName(name);
        u.setSubname(subname);
        u.setBirthdate(date);
        int phonenumber = Integer.parseInt(phone);
        u.setPhone(phonenumber);

        if (!"".equals(oldpassword) & !"".equals(newpassword)) {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String hashedOldPassword = passwordEncoder.encode(oldpassword);
            System.out.println(hashedOldPassword);
            if (passwordEncoder.matches(oldpassword, u.getPassword())) {
                String hashedNewPassword = passwordEncoder.encode(newpassword);
                u.setPassword(hashedNewPassword);
            } else {
                redirectAttrs.addFlashAttribute("editprofile", "You must enter your old password.");
                return "redirect:profile.html";
            }

        }
        userService.edit(u);
        redirectAttrs.addFlashAttribute("editprofile", "Your profile has been updated!");
        session.setAttribute("namesession", u.getName());
        return "redirect:profile.html";
    }
    return "";
}

From source file:com.github.fauu.natrank.web.controller.AdminController.java

@RequestMapping(value = "/bcrypt-enc/{text}", method = RequestMethod.GET)
@ResponseBody/*  w  w  w .  j  a  v  a 2 s .  co m*/
public String bcryptEncode(@PathVariable("text") String text) {
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    return encoder.encode(text);
}

From source file:au.aurin.org.controller.RestController.java

@RequestMapping(method = RequestMethod.POST, value = "/changePassword", produces = "application/json")
@ResponseStatus(HttpStatus.OK)//w  w w.  ja  v  a2s .c om
public @ResponseBody String resetPassword(@RequestHeader("X-AURIN-USER-ID") final String roleId,
        @RequestHeader("user_id") final String user_id, @RequestHeader("newPassword") final String password,
        final HttpServletRequest request) {

    if (!roleId.equals(adminUser.getAdminUsername())) {
        logger.info("Incorrect X-AURIN-USER-ID passed: {}.", roleId);
        return null;
    }

    final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    final String hashedPassword = passwordEncoder.encode(password);

    logger.info("*******>> changePassword for user_id ={}  ", user_id);
    try {
        return geodataFinder.changePassword(user_id, hashedPassword);

    } catch (final Exception e) {
        logger.info(e.toString());

    }
    return null;
}

From source file:ch.wisv.areafiftylan.TicketRestIntegrationTest.java

private User createTeamReturnSingleMember() {
    User teamMate = new User("teamMate", new BCryptPasswordEncoder().encode("password"), "teammate@email.com");
    teamMate.getProfile().setAllFields("Team", "Mate", "IloveYOU", Gender.MALE, "Buddy 7", "2826GJ", "Holland",
            "0906-7777", null);
    userRepository.saveAndFlush(teamMate);

    Ticket teamTicket = new Ticket(teamMate, TicketType.REGULAR_FULL, false, false);
    teamTicket.setValid(true);//from ww  w .j  av  a2 s  . co  m
    ticketRepository.saveAndFlush(teamTicket);

    Team team = new Team("Superawesome", user);
    team.addMember(teamMate);
    teamRepository.saveAndFlush(team);

    return teamMate;
}

From source file:au.aurin.org.controller.RestController.java

@RequestMapping(value = "/insertuser", method = RequestMethod.POST)
public @ResponseBody Boolean insertuser(@RequestHeader("X-AURIN-USER-ID") final String roleId,
        @RequestHeader("X-AURIN-PASSWORD") final String rolePw, @RequestHeader("name") final String name,
        @RequestHeader("family") final String family, @RequestHeader("email") final String email,
        @RequestHeader("roles") final String stroles, @RequestHeader("orgs") final String storgs,
        @RequestHeader("apps") final String stapps, @RequestHeader("accs") final String staccs)
        throws MessagingException, IOException {

    if (!(roleId.equals(adminUser.getAdminUsername()) && rolePw.equals(adminUser.getAdminPassword()))) {
        logger.info("incorrect admin credentials");
        return false;
    }// w w w  . j ava2 s.c  o m

    String password = ""; // aurin

    final SecureRandom random = new SecureRandom();
    for (int i = 0; i < 1; i++) {
        password = new BigInteger(130, random).toString(32);

        logger.info("random password is :" + password);
    }

    final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    final String hashedPassword = passwordEncoder.encode(password);

    logger.info("hashedPassword is :" + hashedPassword);

    // ALTER TABLE users ADD COLUMN uuid character varying(100);
    // for (int i = 1; i < 150; i++) {
    // final UUID uuid = UUID.randomUUID();
    // final String randomUUIDString = uuid.toString();
    // System.out.println("update users set uuid ='" + randomUUIDString
    // + "' where user_id=" + i + ";");
    // }

    // Alter TABLE organisations Drop Constraint fk_contact_id
    // Alter TABLE organisations alter column contact_id DROP NOT NULL;
    // Alter TABLE roles Add Constraint users_role UNIQUE (rolename);
    // Alter TABLE organisations Add Constraint users_orgs UNIQUE (orgname);
    // Alter TABLE application Add Constraint users_apps UNIQUE (appname);
    // Alter TABLE acclvls Add Constraint users_acclvl UNIQUE (acclvlname);

    final UUID uuid = UUID.randomUUID();
    final String randomUUIDString = uuid.toString();

    logger.info("randomUUIDString is :" + randomUUIDString);

    final long user_id = geodataFinder.InsertUser(email, name, family, hashedPassword, randomUUIDString);

    Boolean lsw = true;
    if (user_id == 0) {
        lsw = false;
    } else {
        final String[] orgs = storgs.split(",");
        for (final String st : orgs) {
            if (st.length() > 0) {
                if (geodataFinder.InsertOrgs(st, user_id) == 0) {
                    lsw = false;
                }
            }
        }
        final String[] apps = stapps.split(",");
        for (final String st : apps) {
            if (st.length() > 0) {
                if (geodataFinder.InsertApps(st, user_id) == 0) {
                    lsw = false;
                }
            }
        }
        final String[] roles = stroles.split(",");
        for (final String st : roles) {
            if (st.length() > 0) {
                if (geodataFinder.InsertRoles(st, user_id) == 0) {
                    lsw = false;
                }
            }
        }
        final String[] accs = staccs.split(",");

        for (final String st : accs) {
            if (st.length() > 0) {
                if (geodataFinder.InsertAcclvl(st, user_id) == 0) {
                    lsw = false;
                }
            }
        }
        if (geodataFinder.InsertAgreement(user_id) == 0) {
            lsw = false;
        }
    }

    if (lsw == false) {

        return false;

    } else {

        // //////////////// works
        // final Properties props = new Properties();
        // props.put("mail.smtp.starttls.enable", "true");
        // props.put("mail.smtp.host", "smtp.unimelb.edu.au");
        // props.put("mail.smtp.port", "587");
        // props.put("mail.smtp.auth", "true");
        // final Session session = Session.getDefaultInstance(props,
        // new javax.mail.Authenticator() {
        // @Override
        // protected PasswordAuthentication getPasswordAuthentication() {
        // return new PasswordAuthentication("ashamakhy", "*******");
        // }
        // });
        // try {
        //
        // final Message message = new MimeMessage(session);
        // // message.setFrom(new InternetAddress("alireza.shamakhy@gmail.com"));
        // message.setFrom(new
        // InternetAddress("alireza.shamakhy@unimelb.edu.au"));
        // message.setRecipients(Message.RecipientType.TO,
        // InternetAddress.parse("alireza.shamakhy@gmail.com"));
        // message.setSubject("Testing Subject");
        // message.setText("Dear Mail Crawler,"
        // + "\n\n No spam to my email, please!");
        //
        // Transport.send(message);
        //
        // System.out.println("Done");
        //
        // } catch (final MessagingException e) {
        // throw new RuntimeException(e);
        // }

        // final String clink = classmail.getUrl() + "/authchangepassword/"
        // + randomUUIDString;
        //
        // final String msg = "<br>Your current password is : " + password
        // + " <br> please change it using link: <br> <a href='" + clink
        // + "'> change password </a>";
        //
        // final String subject = "Workbench Access";
        //
        // final String from = classmail.getFrom();
        // final String to = email;
        //
        // try {
        // final Message message = new MimeMessage(getSession());
        //
        // message.addRecipient(RecipientType.TO, new InternetAddress(to));
        // message.addFrom(new InternetAddress[] { new InternetAddress(from) });
        //
        // message.setSubject(subject);
        // message.setContent(msg, "text/html");
        //
        // Transport.send(message);
        // logger.info("Email sent to:" + email);
        // } catch (final MessagingException mex) {
        // logger.info(mex.toString());
        // return false;
        // }
        final String[] apps = stapps.split(",");
        final List<String> lst = new ArrayList<String>();
        for (final String st : apps) {
            if (st.length() > 0) {
                lst.add(geodataFinder.FindApp(st));//
            }
        }
        final String fullname = name + " " + family;
        return sendEmail(randomUUIDString, password, email, lst, fullname);

        // return true;

    }

}

From source file:au.aurin.org.controller.RestController.java

@RequestMapping(value = "/sendEmailLinkPasswordChange", method = RequestMethod.POST)
public @ResponseBody Boolean sendEmailLinkPasswordChange(@RequestHeader("X-AURIN-USER-ID") final String roleId,
        @RequestHeader("X-AURIN-PASSWORD") final String rolePw, @RequestHeader("email") final String email) {
    try {/*from ww w. ja  v  a 2s.  com*/
        final String uuid = geodataFinder.getUuidFromEmail(email);
        if (uuid.length() > 0) {
            String password = ""; // aurin

            final SecureRandom random = new SecureRandom();
            for (int i = 0; i < 1; i++) {
                password = new BigInteger(130, random).toString(32);

                logger.info("random password is :" + password);
            }

            final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            final String hashedPassword = passwordEncoder.encode(password);

            logger.info("hashedPassword is :" + hashedPassword);
            geodataFinder.changeuuidPassword(uuid, hashedPassword);

            return sendEmail(uuid, password, email, null, "");

        }

    } catch (final Exception e) {
        logger.info(e.toString());
        return false;

    }
    return false;

}

From source file:au.aurin.org.controller.RestController.java

@RequestMapping(method = RequestMethod.GET, value = "/authchangepassword/{id}")
public String webchangePassword(@PathVariable("id") final String id, final Model model) {

    final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    // final String hashedPassword = passwordEncoder.encode(password);

    logger.info("*******>> changePassword for uuid ={}  ", id);

    final String out = geodataFinder.getUserID(id);
    if (out.length() > 0) {

        model.addAttribute("msg", classmail.getUrl());
        model.addAttribute("id", out);
        return "changepass";
    }/*from w w w. jav a 2 s  . c  o m*/
    return "403";

}

From source file:au.aurin.org.controller.RestController.java

@RequestMapping(method = RequestMethod.POST, value = "/changeoldpassword")
public @ResponseBody Boolean changeoldPassword(@RequestHeader("uuid") final String uuid,
        @RequestHeader("oldpassword") final String oldpassword,
        @RequestHeader("newpassword") final String newpassword, final HttpServletRequest request) {
    try {//  www  . j  a  va  2 s .  c  o  m
        logger.info("*******>> changeoldpassword for uuid={}  ", uuid);
        final String password = geodataFinder.getPassID(uuid);
        if (password.length() > 0) {

            final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

            final boolean isMatch = passwordEncoder.matches(oldpassword, password);

            if (isMatch == true) {
                logger.info("*******>> changeoldpassword passwords are match. now assigning new password. ");
                final String hashednewPassword = passwordEncoder.encode(newpassword);
                return geodataFinder.changeuuidPassword(uuid, hashednewPassword);
            }
        }

    } catch (final Exception e) {
        logger.info("Error in changeoldPassword is : " + e.toString());

    }
    return false;
}

From source file:org.apache.kylin.rest.security.PasswordPlaceholderConfigurer.java

public static void main(String[] args) {
    if (args.length != 2) {
        printUsage();// w w  w  .j  a va  2s . c  om
        System.exit(1);
    }

    String encryptMethod = args[0];
    String passwordTxt = args[1];
    if ("AES".equalsIgnoreCase(encryptMethod)) {
        // for encrypt password like LDAP password
        System.out.println(encryptMethod + " encrypted password is: ");
        System.out.println(encrypt(passwordTxt));
    } else if ("BCrypt".equalsIgnoreCase(encryptMethod)) {
        // for encrypt the predefined user password, like ADMIN, MODELER.
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        System.out.println(encryptMethod + " encrypted password is: ");
        System.out.println(bCryptPasswordEncoder.encode(passwordTxt));
    } else {
        printUsage();
        System.exit(1);
    }
}