Example usage for org.apache.commons.codec.digest DigestUtils sha256Hex

List of usage examples for org.apache.commons.codec.digest DigestUtils sha256Hex

Introduction

In this page you can find the example usage for org.apache.commons.codec.digest DigestUtils sha256Hex.

Prototype

public static String sha256Hex(String data) 

Source Link

Usage

From source file:net.orzo.lib.Strings.java

/**
 *
 */// w  w w.j ava  2  s  .  co  m
public Object hash(String value, String algorithm) {
    if (value == null) {
        throw new RuntimeException("null value not accepted in hash() function");
    }
    switch (algorithm.toLowerCase()) {
    case "md5":
        return DigestUtils.md5Hex(value);
    case "sha1":
        return DigestUtils.sha1Hex(value);
    case "sha256":
        return DigestUtils.sha256Hex(value);
    case "sha384":
        return DigestUtils.sha384Hex(value);
    case "sha512":
        return DigestUtils.sha512Hex(value);
    default:
        throw new RuntimeException(String.format("Unknown hash function '%s'", algorithm));
    }
}

From source file:com.boyuanitsm.pay.alipay.util.AlipayCore.java

/** 
 * ??//from ww w. j  av a2  s . c o  m
 * @param strFilePath 
 * @param file_digest_type ?
 * @return ?
 */
public static String getAbstract(String strFilePath, String file_digest_type) throws IOException {
    PartSource file = new FilePartSource(new File(strFilePath));
    if (file_digest_type.equals("MD5")) {
        return DigestUtils.md5Hex(file.createInputStream());
    } else if (file_digest_type.equals("SHA")) {
        return DigestUtils.sha256Hex(file.createInputStream());
    } else {
        return "";
    }
}

From source file:com.seventh_root.ld33.common.player.Player.java

public void setPassword(String password) throws SQLException {
    passwordSalt = RandomStringUtils.randomAlphanumeric(32);
    passwordHash = DigestUtils.sha256Hex(password + passwordSalt);
}

From source file:eu.dime.userresolver.service.user.UserService.java

/**
 * /*from   w ww .j av a2  s  .  c  om*/
 * http://[url]/register?said=[said]&name=[name]&surname=[surname]&nickname=[nickname]
 * 
 * {
  *   version: "0.1",
  *   result:
  *      { name: "NAME,"
  *        surname: "SURNAME",
  *        nickname: "NICKNAME",
  *        said: "SAID"
  *      }
 *   }
 * 
 */
@POST
@Path("/register")
@Consumes("application/x-www-form-urlencoded")
@Produces("application/json")
public Response register(@FormParam("said") String said, @FormParam("name") String name,
        @FormParam("surname") String surname, @FormParam("nickname") String nickname) {

    LOG.info("Register user request: {} , {} , {} , {}", new Object[] { said, name, surname, nickname });

    if (said.equals(""))
        return Response.ok(new ErrorResponse("Missing SAID")).status(400).build();

    User user = new User(said, name, surname, nickname);

    String key = RandomStringUtils.randomAlphanumeric(20);
    user.setKey(DigestUtils.sha256Hex(key));

    try {
        userProvider.register(user);
    } catch (IllegalArgumentException e) {
        return Response.ok(new ErrorResponse(e.getMessage())).status(400).build();
    }

    RegisterResponse response = new RegisterResponse();
    response.result = user;
    response.key = key;

    return Response.ok(response).build();
}

From source file:com.supinfo.supfriends.ejb.controller.UserController.java

public String login() {

    String passwordCrypted = DigestUtils.sha256Hex(password);
    loggedUser = userFacade.login(username, passwordCrypted);

    if (null == loggedUser) {
        errorMessage = "Le nom d'utilisateur ou le mot de passe est incorrect.";
        return null;
    }//from w  ww .j  a v  a  2 s.  com

    username = null;
    password = null;
    errorMessage = null;
    HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();
    //HttpServletResponse res = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("username",
            loggedUser.getUserName());
    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("id", loggedUser.getId());
    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("password", passwordCrypted);

    req.getSession().setAttribute("username", loggedUser.getUserName());
    req.getSession().setAttribute("id", loggedUser.getId());
    req.getSession().setAttribute("password", passwordCrypted);

    return "connected_home?faces-redirect=true";
}

From source file:co.cask.hydrator.transforms.Hasher.java

@Override
public void transform(StructuredRecord in, Emitter<StructuredRecord> emitter) throws Exception {
    StructuredRecord.Builder builder = StructuredRecord.builder(in.getSchema());

    List<Schema.Field> fields = in.getSchema().getFields();
    for (Schema.Field field : fields) {
        String name = field.getName();
        if (okToHash(name) && field.getSchema().getType() == Schema.Type.STRING) {
            String value = in.get(name);
            String digest = value;
            switch (config.hash.toLowerCase()) {
            case "md2":
                digest = DigestUtils.md2Hex(value);
                break;
            case "md5":
                digest = DigestUtils.md5Hex(value);
                break;
            case "sha1":
                digest = DigestUtils.sha1Hex(value);
                break;
            case "sha256":
                digest = DigestUtils.sha256Hex(value);
                break;
            case "sha384":
                digest = DigestUtils.sha384Hex(value);
                break;
            case "sha512":
                digest = DigestUtils.sha256Hex(value);
                break;
            }//  w  w  w.j a v a  2 s.  c o  m
            builder.set(name, digest);
        } else {
            builder.set(name, in.get(name));
        }
    }
    emitter.emit(builder.build());
}

From source file:alfio.manager.FileUploadManager.java

public String insertFile(UploadBase64FileModification file) {
    String digest = DigestUtils.sha256Hex(file.getFile());

    if (Integer.valueOf(1).equals(repository.isPresent(digest))) {
        return digest;
    }/*from ww  w  . java 2s  .  co m*/

    LobHandler lobHandler = new DefaultLobHandler();

    jdbc.getJdbcOperations().execute(repository.uploadTemplate(),
            new AbstractLobCreatingPreparedStatementCallback(lobHandler) {
                @Override
                protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {
                    ps.setString(1, digest);
                    ps.setString(2, file.getName());
                    ps.setLong(3, file.getFile().length);
                    lobCreator.setBlobAsBytes(ps, 4, file.getFile());
                    ps.setString(5, file.getType());
                    ps.setString(6, Json.GSON.toJson(getAttributes(file)));
                }
            });
    return digest;
}

From source file:com.whizzosoftware.hobson.bootstrap.api.hub.OSGIHubManager.java

@Override
public void setHubPassword(String userId, String hubId, PasswordChange change) {
    try {/*from w w  w  .java2  s .c om*/
        Configuration config = getConfiguration();
        Dictionary props = getConfigurationProperties(config);

        // verify the old password
        String shaOld = DigestUtils.sha256Hex(change.getCurrentPassword());
        String hubPassword = (String) props.get(ADMIN_PASSWORD);
        if (hubPassword != null && !hubPassword.equals(shaOld)) {
            throw new HobsonRuntimeException("The current hub password is invalid");
        }

        // verify the password meets complexity requirements
        if (!change.isValid()) {
            throw new HobsonInvalidRequestException("New password does not meet complexity requirements");
        }

        // set the new password
        props.put(ADMIN_PASSWORD, DigestUtils.sha256Hex(change.getNewPassword()));

        updateConfiguration(config, props);
    } catch (IOException e) {
        throw new HobsonRuntimeException("Error setting hub password", e);
    }
}

From source file:com.jivesoftware.sdk.service.instance.action.InstanceRegisterAction.java

@Nonnull
public SortedMap<String, String> toSortedMap() {
    // Encode the client-secret
    String encodedClientSecret = (clientSecret != null) ? DigestUtils.sha256Hex(clientSecret) : clientSecret;
    SortedMap<String, String> sortedMap = Maps.newTreeMap();
    sortedMap.put(CLIENT_ID, clientId);//from ww  w .  jav  a 2 s  .  com
    sortedMap.put(CLIENT_SECRET, encodedClientSecret);
    sortedMap.put(CODE, code);
    sortedMap.put(JIVE_SIGNATURE_URL, jiveSignatureURL);
    sortedMap.put(JIVE_URL, jiveUrl);
    sortedMap.put(SCOPE, scope);
    sortedMap.put(TENANT_ID, tenantId);
    sortedMap.put(TIMESTAMP, timestamp);
    return sortedMap;
}

From source file:com.tilab.fiware.metaware.rest.AuthRequestFilter.java

/**
 * Implementation of the filter method.//from  ww w.  ja v  a 2s  .  c o  m
 *
 * @param crc The ContainerRequestContext object
 * @throws WebApplicationException
 */
@Override
public void filter(ContainerRequestContext crc) throws WebApplicationException {
    log.debug("Verb: " + crc.getMethod());
    log.debug("Requested Path: " + crc.getUriInfo().getPath());

    String auth = crc.getHeaderString("Authorization");
    String verb = crc.getMethod();
    String path = crc.getUriInfo().getPath();

    // Check if the basic auth string is sent
    if (auth == null) {
        if (path.equals("api-docs")) {
            return; // get access to swagger interface
        }
        throw new ClientErrorException(Status.UNAUTHORIZED.toString(), Status.UNAUTHORIZED.getStatusCode());
    } else {
        String[] uap = null;

        try {
            uap = Util.decodeBasicAuth(auth);
        } catch (Exception e) {
            log.error(e, e);
        }

        if (uap == null || uap.length != 2) { // empty basic auth string
            throw new ClientErrorException(Status.UNAUTHORIZED.toString(), Status.UNAUTHORIZED.getStatusCode());
        } else {
            User user;

            try {
                user = INSTANCE.getUserService().getUserByCredentials(uap[0], DigestUtils.sha256Hex(uap[1])); // compare hashes

                String jsonMsg = INSTANCE.getObjectMapper().writeValueAsString(user);
                log.debug("Current user: " + jsonMsg);
            } catch (ResourceNotFoundException e) {
                log.error(e, e);
                throw new ClientErrorException(Status.UNAUTHORIZED.toString(),
                        Status.UNAUTHORIZED.getStatusCode());
            } catch (JsonProcessingException | ClientErrorException e) {
                log.error(e, e);
                throw new ServerErrorException(Status.INTERNAL_SERVER_ERROR.toString(),
                        Status.INTERNAL_SERVER_ERROR.getStatusCode());
            }

            // Security access check based on roles
            if (!securityRoleFilter(user, verb, path)) {
                log.info(user.getId() + " is not authorized for " + path);
                throw new ClientErrorException(Status.UNAUTHORIZED.toString(),
                        Status.UNAUTHORIZED.getStatusCode());
            }
        }
    }
}