Example usage for org.apache.shiro.crypto.hash Sha256Hash Sha256Hash

List of usage examples for org.apache.shiro.crypto.hash Sha256Hash Sha256Hash

Introduction

In this page you can find the example usage for org.apache.shiro.crypto.hash Sha256Hash Sha256Hash.

Prototype

public Sha256Hash(Object source) 

Source Link

Usage

From source file:$.UsuarioBC.java

License:Open Source License

@Startup
    @Transactional/* w  w  w  .  ja  va  2  s  .  c  o m*/
    public void load() {
        if (findAll().isEmpty()) {

            Permiso pBookmarkRead = new Permiso("bookmark:read");
            permisoDAO.insert(pBookmarkRead);
            Permiso pBookmarkCreate = new Permiso("bookmark:create");
            permisoDAO.insert(pBookmarkCreate);
            Permiso pBookmarkUpdate = new Permiso("bookmark:update");
            permisoDAO.insert(pBookmarkUpdate);
            Permiso pBookmarkDelete = new Permiso("bookmark:destroy");
            permisoDAO.insert(pBookmarkDelete);
            Permiso pBookmarkAll = new Permiso("bookmark:*");
            permisoDAO.insert(pBookmarkAll);
            Permiso pUserAll = new Permiso("user:*");
            permisoDAO.insert(pUserAll);
            Permiso pRolAll = new Permiso("rol:*");
            permisoDAO.insert(pRolAll);
            Permiso pPermisoAll = new Permiso("permiso:*");
            permisoDAO.insert(pPermisoAll);

            // permisos faltantes no asignados
            permisoDAO.insert(new Permiso("user:read"));
            permisoDAO.insert(new Permiso("user:create"));
            permisoDAO.insert(new Permiso("user:update"));
            permisoDAO.insert(new Permiso("user:destroy"));

            permisoDAO.insert(new Permiso("rol:read"));
            permisoDAO.insert(new Permiso("rol:create"));
            permisoDAO.insert(new Permiso("rol:update"));
            permisoDAO.insert(new Permiso("rol:destroy"));

            permisoDAO.insert(new Permiso("permiso:read"));
            permisoDAO.insert(new Permiso("permiso:create"));
            permisoDAO.insert(new Permiso("permiso:update"));
            permisoDAO.insert(new Permiso("permiso:destroy"));

            Rol rAdmin = new Rol("Admin");
            Set<Permiso> lAdmin = new HashSet<Permiso>();
            lAdmin.add(pPermisoAll);
            lAdmin.add(pRolAll);
            lAdmin.add(pUserAll);
            lAdmin.add(pBookmarkAll);
            rAdmin.setPermisos(lAdmin);
            rolDAO.insert(rAdmin);

            Rol rUser = new Rol("User");
            Set<Permiso> lUser = new HashSet<Permiso>();
            lUser.add(pBookmarkAll);
            rUser.setPermisos(lUser);
            rolDAO.insert(rUser);

            Rol rUser2 = new Rol("User Moderator");
            Set<Permiso> lUser2 = new HashSet<Permiso>();
            lUser2.add(pBookmarkRead);
            lUser2.add(pBookmarkUpdate);
            rUser2.setPermisos(lUser2);
            rolDAO.insert(rUser2);

            Usuario uAdmin = new Usuario(true, "Administrator", "admin@admin.com", "Administrator",
                    new Sha256Hash("admin").toHex(), "5441345", "admin");
            Set<Rol> rolesAdmin = new HashSet<Rol>();
            rolesAdmin.add(rAdmin);
            uAdmin.setRoles(rolesAdmin);
            insert(uAdmin);

            Usuario uUser1 = new Usuario(true, "User", "user@user.com", "User", new Sha256Hash("user").toHex(),
                    "787454", "user");
            Set<Rol> rolesUser1 = new HashSet<Rol>();
            rolesUser1.add(rUser);
            uUser1.setRoles(rolesUser1);
            insert(uUser1);

            Usuario uUser2 = new Usuario(true, "User Mod", "usermod@user.com", "User Mod",
                    new Sha256Hash("user2").toHex(), "787454", "user2");
            Set<Rol> rolesUser2 = new HashSet<Rol>();
            rolesUser2.add(rUser2);
            uUser2.setRoles(rolesUser2);
            insert(uUser2);

        }

    }

From source file:$.UsuarioDAO.java

License:Open Source License

public void setHashedPassword(Usuario usuario, String password) {
        usuario.setPwd(new Sha256Hash(password).toHex());
        this.update(usuario);
    }

From source file:$.UsuarioRS.java

License:Open Source License

@POST
    @RequiresPermissions("user:create")
    @Path("/")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response updateUsers(Usuario user) {
        user.setPwd(new Sha256Hash(user.getPwd()).toHex());
        user.setActivo(true);/*w  w  w . ja v  a  2s.  com*/
        usuarioBC.update(user);
        System.out.println("================ Create User: " + user.getUsername() + " ");

        Map<String, Object> root = new HashMap<String, Object>();
        root.put("success", true);
        return Response.ok(root).build();
    }

From source file:$.UsuarioRS.java

License:Open Source License

@PUT
    @Path("/password/{id}")
    @RequiresPermissions("user:update")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> updateUserPassword(@PathParam("id") Long id, Map<String, String> passwords) {
        System.out.println("================ old password: " + passwords.get("password") + " new "
                + passwords.get("newPassword"));
        Usuario user = usuarioBC.findById(id);
        Map<String, Object> root = new HashMap<String, Object>();
        String check = new Sha256Hash(passwords.get("password")).toHex();

        if (check.equals(user.getPwd())) {
            //password correcto, actualizar con newPassword
            user.setPwd(new Sha256Hash(passwords.get("newPassword")).toHex());
            usuarioBC.update(user);//from w ww .j a  va2 s.c  om
            root.put("success", true);
        } else {
            root.put("success", false);
        }

        return root;
    }

From source file:annis.security.ANNISUserRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    Validate.isInstanceOf(String.class, token.getPrincipal());

    String userName = (String) token.getPrincipal();
    if (userName.equals(anonymousUser)) {
        // for anonymous users the user name equals the Password, so hash the user name
        Sha256Hash hash = new Sha256Hash(userName);
        return new SimpleAuthenticationInfo(userName, hash.getBytes(), ANNISUserRealm.class.getName());
    }/*from w w w  .j  a  v a  2  s  . c o  m*/

    User user = confManager.getUser(userName);
    if (user != null) {
        String passwordHash = user.getPasswordHash();
        if (passwordHash != null) {
            if (passwordHash.startsWith("$")) {
                Shiro1CryptFormat fmt = new Shiro1CryptFormat();
                Hash hashCredentials = fmt.parse(passwordHash);
                if (hashCredentials instanceof SimpleHash) {
                    SimpleHash simpleHash = (SimpleHash) hashCredentials;

                    Validate.isTrue(simpleHash.getIterations() == 1,
                            "Hash iteration count must be 1 for every password hash!");

                    // actually set the information from the user file
                    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName,
                            simpleHash.getBytes(), ANNISUserRealm.class.getName());
                    info.setCredentialsSalt(new SerializableByteSource(simpleHash.getSalt()));
                    return info;
                }
            } else {
                // fallback unsalted hex hash
                SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(token.getPrincipal(), passwordHash,
                        ANNISUserRealm.class.getName());
                return info;
            }

        }
    }
    return null;
}

From source file:au.org.theark.study.model.dao.LdapUserDao.java

License:Open Source License

public void updateArkUser(ArkUserVO userVO) throws ArkSystemException {
    try {//from  w w  w.  j  a v a2s .c  om
        // Assuming that all validation is already done update the attributes in LDAP
        LdapName ldapName = new LdapName(ldapDataContextSource.getBasePeopleDn());
        ldapName.add(new Rdn("cn", userVO.getUserName()));

        BasicAttribute sn = new BasicAttribute("sn", userVO.getLastName());
        BasicAttribute givenName = new BasicAttribute("givenName", userVO.getFirstName());
        BasicAttribute email = new BasicAttribute("mail", userVO.getEmail());

        ModificationItem itemSn = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, sn);
        ModificationItem itemGivenName = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, givenName);
        ModificationItem itemEmail = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, email);

        if (userVO.getPassword() != null && userVO.getPassword().length() > 0 && userVO.isChangePassword()) {
            BasicAttribute userPassword = new BasicAttribute("userPassword",
                    new Sha256Hash(userVO.getPassword()).toHex());
            ModificationItem itemPassword = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPassword);
            ldapDataContextSource.getLdapTemplate().modifyAttributes(ldapName,
                    new ModificationItem[] { itemSn, itemGivenName, itemEmail, itemPassword });
        } else {
            ldapDataContextSource.getLdapTemplate().modifyAttributes(ldapName,
                    new ModificationItem[] { itemSn, itemGivenName, itemEmail });
        }

    } catch (InvalidNameException ine) {
        throw new ArkSystemException("A System error has occured");
    }

}

From source file:au.org.theark.study.model.dao.LdapUserDao.java

License:Open Source License

protected void mapToContext(String username, String firstName, String lastName, String email, String password,
        DirContextOperations dirCtxOperations) {

    dirCtxOperations.setAttributeValues("objectClass",
            new String[] { "inetOrgPerson", "organizationalPerson", "person" });
    dirCtxOperations.setAttributeValue("cn", username);
    dirCtxOperations.setAttributeValue("sn", lastName);
    dirCtxOperations.setAttributeValue("givenName", firstName);
    dirCtxOperations.setAttributeValue("mail", email);
    dirCtxOperations.setAttributeValue("userPassword", new Sha256Hash(password).toHex());// Service will always hash it.
}

From source file:au.org.theark.study.model.dao.LdapUserDao.java

License:Open Source License

public void update(ArkUserVO userVO) throws ArkSystemException {
    log.debug("update() invoked: Updating user details in LDAP");
    try {//w  w  w .j  av  a 2  s.c  o m
        // Assuming that all validation is already done update the attributes in LDAP
        LdapName ldapName = new LdapName(ldapDataContextSource.getBasePeopleDn());
        ldapName.add(new Rdn("cn", userVO.getUserName()));

        BasicAttribute sn = new BasicAttribute("sn", userVO.getLastName());
        BasicAttribute givenName = new BasicAttribute("givenName", userVO.getFirstName());
        BasicAttribute email = new BasicAttribute("mail", userVO.getEmail());

        ModificationItem itemSn = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, sn);
        ModificationItem itemGivenName = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, givenName);
        ModificationItem itemEmail = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, email);

        // Check if password needs to be modified. Make sure client validation is done.
        // TODO Also enforce the validation check here.
        if (userVO.isChangePassword()) {
            BasicAttribute userPassword = new BasicAttribute("userPassword",
                    new Sha256Hash(userVO.getPassword()).toHex());
            ModificationItem itemPassword = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPassword);
            ldapDataContextSource.getLdapTemplate().modifyAttributes(ldapName,
                    new ModificationItem[] { itemSn, itemGivenName, itemEmail, itemPassword });
        } else {
            ldapDataContextSource.getLdapTemplate().modifyAttributes(ldapName,
                    new ModificationItem[] { itemSn, itemGivenName, itemEmail });
        }
    } catch (InvalidNameException ine) {
        throw new ArkSystemException("A System error has occured");
    }
}

From source file:br.com.diego.midia.managedBean.RegistrarUsuarioMB.java

public void submit() {
    try {// w  w w.j  a v a  2s  .  c  om
        usuario.setSenha(new Sha256Hash(usuario.getSenha()).toHex());
        usuarioBean.salvar(usuario);
        usuario = new Usuario();
        Messages.addGlobalInfo("Registration suceed, new user ID is: {0}", usuario.getId());
    } catch (RuntimeException e) {
        Messages.addGlobalError("Registration failed: {0}", e.getMessage());
        e.printStackTrace(); // TODO: logger.
    }
}

From source file:br.com.diego.shiro.Register.java

public void submit() {
    try {//from w  w w  .  j ava  2 s.  co  m
        user.setPassword(new Sha256Hash(user.getPassword()).toHex());
        service.create(user);
        Messages.addGlobalInfo("Registration suceed, new user ID is: {0}", user.getId());
    } catch (RuntimeException e) {
        Messages.addGlobalError("Registration failed: {0}", e.getMessage());
        e.printStackTrace(); // TODO: logger.
    }
}