Example usage for org.springframework.security.crypto.keygen KeyGenerators string

List of usage examples for org.springframework.security.crypto.keygen KeyGenerators string

Introduction

In this page you can find the example usage for org.springframework.security.crypto.keygen KeyGenerators string.

Prototype

public static StringKeyGenerator string() 

Source Link

Document

Creates a StringKeyGenerator that hex-encodes SecureRandom keys of 8 bytes in length.

Usage

From source file:io.stallion.utils.Encrypter.java

public static String encryptString(String password, String value) {
    String salt = KeyGenerators.string().generateKey();
    SecretKeySpec skeySpec = makeKeySpec(password, salt);
    byte[] iv = KeyGenerators.secureRandom(16).generateKey();
    String ivString = Hex.encodeHexString(iv);

    try {//from ww w.j a  v  a  2s  .  c om
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new GCMParameterSpec(128, iv));
        /*
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec,
        new IvParameterSpec(iv));
        */

        byte[] encrypted = cipher.doFinal(value.getBytes(Charset.forName("UTF-8")));
        String s = StringUtils.strip(new Base32().encodeAsString(encrypted), "=").toLowerCase();
        // Strip line breaks
        s = salt + ivString + s.replaceAll("(\\n|\\r)", "");
        return s;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:de.steilerdev.myVerein.server.model.User.java

/**
 * Setting the password. The password is automatically hashed and the salt is randomly re-generated.
 * @param password The new plain text password.
 *//*from  www  .j  av  a  2  s  .com*/
public void setPassword(String password) {
    salt = KeyGenerators.string().generateKey();
    PasswordEncoder passwordEncoder = new PasswordEncoder();
    this.password = passwordEncoder.encodePassword(password, salt);
}

From source file:mx.edu.um.mateo.general.web.UsuarioController.java

@Transactional
@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, HttpServletResponse response, @Valid Usuario usuario,
        BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam Boolean enviaCorreo) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }/*from  w  ww .  java2s  .co m*/
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        List<Rol> roles = obtieneRoles();
        modelo.addAttribute("roles", roles);
        return "admin/usuario/nuevo";
    }

    String password = null;
    try {
        log.debug("Evaluando roles {}", request.getParameterValues("roles"));
        String[] roles = request.getParameterValues("roles");
        if (roles == null || roles.length == 0) {
            log.debug("Asignando ROLE_USER por defecto");
            roles = new String[] { "ROLE_USER" };
        }
        Long almacenId = (Long) request.getSession().getAttribute("almacenId");
        password = KeyGenerators.string().generateKey();
        usuario.setPassword(password);
        usuario = usuarioDao.crea(usuario, almacenId, roles);

        if (enviaCorreo) {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setTo(usuario.getCorreo());
            helper.setSubject(messageSource.getMessage("envia.correo.password.titulo.message", new String[] {},
                    request.getLocale()));
            helper.setText(messageSource.getMessage("envia.correo.password.contenido.message",
                    new String[] { usuario.getNombre(), usuario.getUsername(), password }, request.getLocale()),
                    true);
            mailSender.send(message);
        }

    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear al usuario", e);
        errors.rejectValue("username", "campo.duplicado.message", new String[] { "username" }, null);
        List<Rol> roles = obtieneRoles();
        modelo.addAttribute("roles", roles);
        return "admin/usuario/nuevo";
    } catch (MessagingException e) {
        log.error("No se pudo enviar la contrasena por correo", e);

        redirectAttributes.addFlashAttribute("message", "usuario.creado.sin.correo.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { usuario.getUsername(), password });

        return "redirect:/admin/usuario/ver/" + usuario.getId();
    }

    redirectAttributes.addFlashAttribute("message", "usuario.creado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { usuario.getUsername() });

    return "redirect:/admin/usuario/ver/" + usuario.getId();
}

From source file:org.fao.geonet.domain.User.java

public static String getRandomPassword() {
    StringKeyGenerator generator = KeyGenerators.string();
    return generator.generateKey().substring(0, 8);
}