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

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

Introduction

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

Prototype

public String encode(CharSequence rawPassword) 

Source Link

Usage

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

@RequestMapping(method = RequestMethod.POST, value = "/changePassword", produces = "application/json")
@ResponseStatus(HttpStatus.OK)/* w w w.  j  a  va2s  . c  o m*/
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: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 w ww  .  j a v  a 2 s . c o m
        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(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;
    }/*from   w w  w .j  a v  a  2  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(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 {//from   w w w .  j a  v a 2s  .com
        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:com.siblinks.ws.service.impl.UserServiceImpl.java

/**
 * {@inheritDoc}//from  w  w  w  .ja  v a2  s  .c o m
 */
@Override
@RequestMapping(value = "/registerUser", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<Response> registerUser(@RequestBody final String jsonRegister) {
    SimpleResponse response = null;
    try {
        JSONObject jsonObject = new JSONObject(jsonRegister);
        String username = jsonObject.getString(Parameters.USER_NAME);
        //
        List<Object> readObject = dao.readObjects(SibConstants.SqlMapper.SQL_SIB_REGISTER_USER_EXIST,
                new Object[] { username });
        //
        boolean status = Boolean.FALSE;
        if (CollectionUtils.isEmpty(readObject)) {
            BCryptPasswordEncoder ecy = new BCryptPasswordEncoder(SibConstants.LENGHT_AUTHENTICATION);
            Object[] queryParams = { username, ecy.encode(jsonObject.getString(Parameters.PASSWORD)),
                    environment.getProperty("directoryImageAvatar"), username };
            boolean msgs = dao.insertUpdateObject(SibConstants.SqlMapper.SQL_SIB_REGISTER_USER, queryParams);
            readObject = new ArrayList<Object>();
            if (msgs) {
                readObject.add("Successfully registered");
                status = Boolean.TRUE;
            } else {
                readObject.add("Fail registration");
            }
        } else {
            readObject = new ArrayList<Object>();
            readObject.add("Email address is already registered");
        }

        response = new SimpleResponse("" + status, readObject);
    } catch (Exception e) {
        logger.error(e.getMessage());
        response = new SimpleResponse(SibConstants.FAILURE, "user", "registerUser", e.getMessage());
    }
    return new ResponseEntity<Response>(response, HttpStatus.OK);
}

From source file:com.siblinks.ws.service.impl.UserServiceImpl.java

/**
 * {@inheritDoc}//  ww w  . j  a  v a  2s . co  m
 */
@Override
@RequestMapping(value = "/changePasswordForgot", method = RequestMethod.POST)
public ResponseEntity<Response> changePasswordForgot(@RequestBody final String jsonData) {
    SimpleResponse response = null;
    try {
        // read json data
        JSONObject jsonObject = new JSONObject(jsonData);
        String token = jsonObject.getString("token");
        String newPwd = jsonObject.getString("newPwd");

        BCryptPasswordEncoder ecy = new BCryptPasswordEncoder(SibConstants.LENGHT_AUTHENTICATION);
        // check old password correct or not
        boolean status = dao.insertUpdateObject(SibConstants.SqlMapper.SQL_SIB_RESET_PASSWORD,
                new Object[] { ecy.encode(newPwd), token });
        if (status) {
            response = new SimpleResponse(SibConstants.SUCCESS, "", "changePasswordForgot", "Success");
        } else {
            response = new SimpleResponse(SibConstants.FAILURE, "", "changePasswordForgot", "Failure");
        }

    } catch (Exception e) {
        logger.error(e.getMessage());
        response = new SimpleResponse(SibConstants.FAILURE, "user", "changePasswordForgot", e.getMessage());
    }
    return new ResponseEntity<Response>(response, HttpStatus.OK);
}

From source file:com.siblinks.ws.service.impl.UserServiceImpl.java

/**
 * {@inheritDoc}//from w w  w  .  j av  a  2  s  .  c om
 */
@Override
@RequestMapping(value = "/changePassword", method = RequestMethod.POST)
public ResponseEntity<Response> changePassword(@RequestBody final RequestData request) {
    SimpleResponse response = null;
    try {
        BCryptPasswordEncoder ecy = new BCryptPasswordEncoder(SibConstants.LENGHT_AUTHENTICATION);
        // check old password correct or not
        Object[] queryParams = { request.getRequest_user().getUsername() };
        List<Object> readObject = dao.readObjects(SibConstants.SqlMapper.SQL_SIB_LOGIN_USER, queryParams);
        if (!CollectionUtils.isEmpty(readObject)) {
            // Verify password
            // String rawPwd =
            // ecy.encode(request.getRequest_user().getPassword());
            Map<String, String> user = (HashMap<String, String>) readObject.get(SibConstants.NUMBER.ZERO);
            String encryptPwd = user.get(Parameters.PASSWORD);
            if (encryptPwd != null && !StringUtils.isEmpty(encryptPwd)) {
                // Verify old password
                if (CommonUtil.verifyPassword(request.getRequest_user().getPassword(), encryptPwd)) {
                    // Update new password
                    boolean status = dao.insertUpdateObject(SibConstants.SqlMapper.SQL_UPDATE_PASSWORD,
                            new Object[] { ecy.encode(request.getRequest_user().getNewpassword()),
                                    request.getRequest_user().getUsername() });
                    if (status) {
                        response = new SimpleResponse("" + Boolean.TRUE, request.getRequest_data_type(),
                                request.getRequest_data_method(), "Changed Password Successfully");
                    } else {
                        response = new SimpleResponse(SibConstants.FAILURE, request.getRequest_data_type(),
                                request.getRequest_data_method(),
                                "Change password is failed. Please contact with administrator");
                    }
                } else {
                    response = new SimpleResponse(SibConstants.FAILURE, request.getRequest_data_type(),
                            request.getRequest_data_method(), "Old password is not correctly");

                }
            } else {
                // User is exist
                response = new SimpleResponse(SibConstants.FAILURE, request.getRequest_data_type(),
                        request.getRequest_data_method(), "Your account can not change password.");
            }
        }

    } catch (Exception e) {
        logger.error(e.getMessage());
        response = new SimpleResponse(SibConstants.FAILURE, "user", "changePassword", e.getMessage());
    }
    return new ResponseEntity<Response>(response, HttpStatus.OK);
}

From source file:com.siblinks.ws.service.impl.UserServiceImpl.java

/**
 * {@inheritDoc}//  www. j ava  2  s .  co m
 */
@Override
@RequestMapping(value = "/registerAdminMentor", method = RequestMethod.POST)
public ResponseEntity<Response> registerAdminMentor(@RequestBody final String jsonRegister) {
    SimpleResponse response = null;
    try {
        JSONObject objRequest = new JSONObject(jsonRegister);
        String userName = objRequest.getString(Parameters.USER_NAME);
        String role = objRequest.getString(Parameters.ROLE);
        BCryptPasswordEncoder ecy = new BCryptPasswordEncoder(SibConstants.LENGHT_AUTHENTICATION);
        List<Object> userResponse = dao.readObjects(SibConstants.SqlMapper.SQL_SIB_REGISTER_USER_EXIST,
                new Object[] { userName });
        String message = "";
        boolean status = false;
        boolean isRegisterAdmin = role.equals("A");
        if (CollectionUtils.isEmpty(userResponse) || userResponse == null) {
            String dob = objRequest.getString(Parameters.DOB);
            if (!StringUtils.isEmpty(dob)) {
                SimpleDateFormat formatter = new SimpleDateFormat("dd MMM, yyyy", Locale.getDefault());
                Date date = formatter.parse(dob);
                dob = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
            } else {
                dob = null;
            }

            String rawPwd = isRegisterAdmin ? objRequest.getString(Parameters.PASSWORD)
                    : CommonUtil.getInstance().getAutoGeneratePwd();
            String pwdEncrypt;
            Object[] queryParams = null;
            if (!StringUtils.isEmpty(rawPwd)) {
                pwdEncrypt = ecy.encode(rawPwd);
            } else {
                pwdEncrypt = ecy.encode(SibConstants.DEFAULT_PWD);
                rawPwd = SibConstants.DEFAULT_PWD;
            }
            if (isRegisterAdmin) {
                queryParams = new Object[] { userName, role, objRequest.getString(Parameters.FIRST_NAME),
                        objRequest.getString(Parameters.LAST_NAME), pwdEncrypt, dob,
                        objRequest.getString(Parameters.ACTIVE_PLAG) };
                status = dao.insertUpdateObject(SibConstants.SqlMapper.SQL_ADMIN_ADD_ANOTHER_ADMIN,
                        queryParams);
            } else {
                queryParams = new Object[] { userName, role, objRequest.getString(Parameters.FIRST_NAME),
                        objRequest.getString(Parameters.LAST_NAME), pwdEncrypt, dob,
                        objRequest.getString(Parameters.BIO), objRequest.getString(Parameters.SCHOOL),
                        objRequest.getString(Parameters.DEFAULT_SUBJECT_ID),
                        objRequest.getString(Parameters.ACCOMPLISHMENT),
                        objRequest.getString(Parameters.ACTIVE_PLAG) };
                status = dao.insertUpdateObject(SibConstants.SqlMapper.SQL_ADMIN_ADD_ANOTHER_MENTOR,
                        queryParams);
            }
            if (status) {
                String urlLogin = "";
                String paramGetUrlDomain = isRegisterAdmin ? SibConstants.DOMAIN_NAME_ADMIN
                        : SibConstants.DOMAIN;
                List<Object> readObjects = dao.readObjects(SibConstants.SqlMapper.SQL_GET_ADDRESS_WEB,
                        new Object[] { paramGetUrlDomain });
                for (Object object : readObjects) {
                    Map<String, String> mapObject = (HashMap<String, String>) object;
                    urlLogin = mapObject.get(Parameters.VALUE_OF);
                    break;
                }

                urlLogin = isRegisterAdmin ? urlLogin : urlLogin.concat(Parameters.LOGIN_MENTOR_URL);
                // Send email
                try {
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put("userName", userName);
                    map.put("password", rawPwd);
                    map.put("URL_LOGIN", urlLogin);
                    NotifyByEmail notify = new NotifyByEmail();
                    notify.setMailSender(mailSender);
                    notify.setVelocityEngine(velocityEngine);
                    notify.sendHmtlTemplateEmail(null, userName, null, null,
                            environment.getProperty("app.subject-email.registration-mentor"),
                            "MAIL_Notify_5.vm", map);
                    message = "Successfully registered";
                } catch (Exception e) {
                    logger.error(e);
                    status = false;
                    message = "Email not unavailable, Plz check !!";
                }
            } else {
                message = "Fail registration";
            }
        } else {
            status = false;
            message = "Email address is already registered";
        }
        response = new SimpleResponse("" + status, "user", "registerAdminMentor", message);
    } catch (Exception e) {
        logger.error(e.getMessage());
        response = new SimpleResponse(SibConstants.FAILURE, "user", "registerAdminMentor", e.getMessage());
    }
    return new ResponseEntity<Response>(response, HttpStatus.OK);
}

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 av a2s  .com
        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);
    }
}

From source file:org.cloud.mblog.utils.StringHelper.java

public static String encrypt(String plainText) {
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    return passwordEncoder.encode(plainText);
}