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

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

Introduction

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

Prototype

public static String sha512Hex(String data) 

Source Link

Usage

From source file:co.cask.hydrator.plugin.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 (fieldSet.contains(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.sha512Hex(value);
                break;
            }//from   w  ww .  jav a 2s .  co  m
            builder.set(name, digest);
        } else {
            builder.set(name, in.get(name));
        }
    }
    emitter.emit(builder.build());
}

From source file:de.hub.cses.ces.jsf.bean.game.CreationBean.java

/**
 *
 * @return//from w w w  . ja  v  a  2  s.c  om
 */
public String createGame() {

    String value = (String) identifier.getValue();

    if (gameFacade.exists(value)) {
        logger.log(Level.INFO, "schon da");
        String errorMessage = FacesContext.getCurrentInstance().getApplication()
                .getResourceBundle(FacesContext.getCurrentInstance(), "i18n_txts").getString("exists");
        // Add View Faces Message
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, errorMessage);
        // Add the message into context for a specific component
        FacesContext.getCurrentInstance().addMessage(identifier.getClientId(), message);
        return null;
    }

    game.setIdentifier(value);
    String password = game.getPassword();
    if (password != null && !password.isEmpty()) {
        game.setPassword(DigestUtils.sha512Hex(password));
    }
    economy.setGame(game);
    economy.setMarket(market);
    economy.setEconomicData(new EconomicData());
    economy.getEconomicData().setHistoricalEconomicData(new HistoricalEconomicData());
    game.setEconomy(economy);
    gameFacade.create(game);
    logger.log(Level.INFO, "Game {0} created.", game);
    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
    String url = ec.encodeActionURL("/game/setup.xhtml?faces-redirect=true&game-id=" + game.getId());
    return url;
}

From source file:com.remediatetheflag.global.actions.unauth.DoSignupUserAction.java

@Override
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {

    JsonObject json = (JsonObject) request.getAttribute(Constants.REQUEST_JSON);
    JsonElement usernameElement = json.get(Constants.ACTION_PARAM_USERNAME);
    String username = usernameElement.getAsString();

    JsonElement firstNameElement = json.get(Constants.ACTION_PARAM_FIRST_NAME);
    JsonElement lastNameElement = json.get(Constants.ACTION_PARAM_LAST_NAME);
    JsonElement emailElement = json.get(Constants.ACTION_PARAM_EMAIL);
    JsonElement countryElement = json.get(Constants.ACTION_PARAM_COUNTRY);
    JsonElement passwordElement = json.get(Constants.ACTION_PARAM_PASSWORD);
    JsonElement orgInvitationCodeElement = json.get(Constants.ACTION_PARAM_ORG_CODE);

    String firstName = firstNameElement.getAsString();
    String lastName = lastNameElement.getAsString();
    String email = emailElement.getAsString();
    String country = countryElement.getAsString();
    String password = passwordElement.getAsString();
    String orgInvitationCode = orgInvitationCodeElement.getAsString();

    Organization o = hpc.getOrganizationFromInvitationCode(orgInvitationCode);
    if (null == o) {
        MessageGenerator.sendErrorMessage("OrgCodeWrong", response);
        return;/*from  ww  w .  j  a  va  2 s  .co  m*/
    }
    @SuppressWarnings("serial")
    List<User> organizationUsers = hpc.getManagementAllUsers(new HashSet<Organization>() {
        {
            add(o);
        }
    });
    if (organizationUsers.size() >= o.getMaxUsers()) {
        MessageGenerator.sendErrorMessage("MaxUserLimit", response);
        return;
    }

    User existingUser = hpc.getUserFromUsername(username);
    if (existingUser != null) {
        MessageGenerator.sendErrorMessage("UserExists", response);
        return;
    }
    if (!PasswordComplexityUtil.isPasswordComplex(password)) {
        MessageGenerator.sendErrorMessage("WeakPassword", response);
        return;
    }
    Country c = hpc.getCountryFromCode(country);
    if (null == c) {
        logger.error("Invalid data entered for signup for email: " + email);
        MessageGenerator.sendErrorMessage("InvalidData", response);
        return;
    }
    User user = new User();
    user.setEmail(email);
    user.setInvitationCodeRedeemed(orgInvitationCode);
    user.setLastName(lastName);
    user.setUsername(username);
    user.setFirstName(firstName);
    user.setRole(Constants.ROLE_USER);
    String salt = RandomGenerator.getNextSalt();
    String pwd = DigestUtils.sha512Hex(password.concat(salt));
    user.setSalt(salt);
    user.setPassword(pwd);
    user.setStatus(UserStatus.INACTIVE);
    user.setCountry(c);
    user.setScore(0);
    user.setExercisesRun(0);
    user.setEmailVerified(true);
    user.setForceChangePassword(false);
    user.setInstanceLimit(1);
    Date today = new Date();
    user.setJoinedDateTime(today);
    user.setPersonalDataUpdateDateTime(today);
    user.setCredits(10);
    user.setCreatedByUser(null);
    user.setTeam(null);
    user.setDefaultOrganization(o);
    Integer id = hpc.addUser(user);
    if (null != id && id > 0) {
        hpc.decreseOrganizationCodeRedeem(o, orgInvitationCode);
        NotificationsHelper helper = new NotificationsHelper();
        helper.addNewUserAdded(user);
        helper.addWelcomeToRTFNotification(user);
        MessageGenerator.sendSuccessMessage(response);
    } else {
        logger.error("Signup failed at DB-end for email: " + email);
        MessageGenerator.sendErrorMessage("SignupFailed", response);
    }
}

From source file:com.eriwen.gradle.Digest.java

private String digest(final File file, final DigestAlgorithm algorithm) throws IOException {
    final byte[] contentBytes = Files.readAllBytes(file.toPath());
    final String checksum;
    switch (algorithm) {
    case MD5://  www .j  a  va2  s. c o  m
        checksum = DigestUtils.md5Hex(contentBytes);
        break;
    case SHA1:
        checksum = DigestUtils.sha1Hex(contentBytes);
        break;
    case SHA256:
        checksum = DigestUtils.sha256Hex(contentBytes);
        break;
    case SHA512:
        checksum = DigestUtils.sha512Hex(contentBytes);
        break;
    default:
        throw new IllegalArgumentException("Cannot use unknown digest algorithm " + algorithm.toString());
    }
    return checksum;
}

From source file:at.stefanproell.ResultSetVerification.ResultSetVerificationAPI.java

/**
 * Calculate SHA512 hash from input//from  www .j  av a  2s .c o m
 *
 * @param inputString
 * @return
 * @throws NoSuchAlgorithmException
 */
public String calculateSHA512HashFromString(String inputString) {
    try {
        this.crypto.update(inputString.getBytes("utf8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    String hash = DigestUtils.sha512Hex(this.crypto.digest());
    return hash;

}

From source file:com.mimp.controllers.organismo.java

@RequestMapping(value = "/Orgcambiarcontra", method = RequestMethod.GET)
public ModelAndView Orgcambiarcontra_GET(ModelMap map, HttpSession session) {
    Entidad usuario = (Entidad) session.getAttribute("usuario");
    String mensaje = "";
    if (usuario == null) {
        mensaje = "La sesin ha finalizado. Favor identificarse nuevamente";
        map.addAttribute("mensaje", mensaje);
        return new ModelAndView("login", map);
    }//w w  w  .jav  a 2  s  . c o  m
    if (session.getAttribute("oldpass") != null && session.getAttribute("newpass") != null
            && session.getAttribute("newpassconf") != null) {
        String oldpass = (String) session.getAttribute("oldpass");
        String newpass = (String) session.getAttribute("newpass");
        String newpassconf = (String) session.getAttribute("newpassconf");

        oldpass = DigestUtils.sha512Hex(oldpass);
        if (usuario.getPass().equals(oldpass)) {
            if (newpass.equals(newpassconf)) {
                newpass = DigestUtils.sha512Hex(newpass);
                usuario.setPass(newpass);
                ServicioOrganismo.CambiaPass(usuario);
                mensaje = "La contrasea se ha cambiado con exito.";
            } else {
                mensaje = "Las contraseas no coinciden. Favor de reescribir la nueva contrasea.";
            }
        } else {
            mensaje = "Contrasea de usuario incorrecta. Ingrese nuevamente.";
        }

        String pagina = "/Entidad/contra_ent";
        map.addAttribute("mensaje", mensaje);

        session.removeAttribute("oldpass");
        session.removeAttribute("newpass");
        session.removeAttribute("newpassconf");

        return new ModelAndView(pagina, map);
    } else {
        return new ModelAndView("/Entidad/inicio_ent", map);

    }

}

From source file:net.lyonlancer5.mcmp.karasu.util.ModFileUtils.java

public void doHashCheck(File jarFile) {
    if (!hasInitialized)
        initialize();/* w ww. j  av  a 2 s  . com*/

    if (doHashCheck) {
        LOGGER.info("Mod source file located at " + jarFile.getPath());
        if (jarFile.isFile() && !jarFile.getName().endsWith("bin")) {
            try {
                List<String> lines = IOUtils.readLines(new FileInputStream(remoteHashes));
                for (String s : lines) {
                    //version:jarName:md5:sha1:sha256:sha512
                    String[] params = s.split(":");
                    if (params[0].equals(Constants.VERSION)) {
                        if (!params[1].equals(jarFile.getName()))
                            LOGGER.warn("JAR filename has been changed!");

                        FileInputStream fis = new FileInputStream(jarFile);
                        String var0 = DigestUtils.md5Hex(fis);
                        String var1 = DigestUtils.sha1Hex(fis);
                        String var2 = DigestUtils.sha256Hex(fis);
                        String var3 = DigestUtils.sha512Hex(fis);

                        assert ((params[2].equals(var0)) && (params[3].equals(var1)) && (params[4].equals(var2))
                                && (params[5].equals(var3))) : new ValidationError(
                                        "Mod integrity check FAILED: mismatched hashes (Has the mod file been edited?)");

                        LOGGER.info("Validation success!");
                        return;
                    }
                }
            } catch (IOException e) {
                throw new ValidationError("Validation FAILED - I/O error", e);
            }
        } else {
            isDevEnv = true;
            LOGGER.warn(
                    "The mod is currently running on a development environment - Integrity checking will not proceed");
        }
    } else {
        LOGGER.warn("#########################################################################");
        LOGGER.warn("WARNING: Integrity checks have been DISABLED!");
        LOGGER.warn("Hash checks will not be performed - this mod may not run as intended");
        LOGGER.warn("Any changes made to this mod will not be validated, whether it came from");
        LOGGER.warn("a legitimate source or an attempt to insert code into this modification");
        LOGGER.warn("#########################################################################");
    }
}

From source file:com.remediatetheflag.global.actions.auth.management.reviewer.AddUserAction.java

@SuppressWarnings({ "unchecked", "serial", "rawtypes" })
@Override//from   www . j a  v a 2s .  c  om
public void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
    JsonObject json = (JsonObject) request.getAttribute("json");

    User sessionUser = (User) request.getSession().getAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT);

    JsonElement usernameElement = json.get(Constants.ACTION_PARAM_USERNAME);
    JsonElement firstNameElement = json.get(Constants.ACTION_PARAM_FIRST_NAME);
    JsonElement lastNameElement = json.get(Constants.ACTION_PARAM_LAST_NAME);
    JsonElement emailElement = json.get(Constants.ACTION_PARAM_EMAIL);
    JsonElement countryElement = json.get(Constants.ACTION_PARAM_COUNTRY);
    JsonElement passwordElement = json.get(Constants.ACTION_PARAM_PASSWORD);
    JsonElement orgElement = json.get(Constants.ACTION_PARAM_ORG_ID);

    JsonElement roleElement = json.get(Constants.ACTION_PARAM_ROLE_ID);
    JsonElement concurrentExerciseLimitElement = json.get(Constants.ACTION_PARAM_CONCURRENT_EXERCISE_LIMIT);
    JsonElement creditsElement = json.get(Constants.ACTION_PARAM_CREDITS);
    JsonElement passwordChangeElement = json.get(Constants.ACTION_PARAM_FORCE_PASSWORD_CHANGE);

    String username = usernameElement.getAsString();
    String firstName = firstNameElement.getAsString();
    String lastName = lastNameElement.getAsString();
    String email = emailElement.getAsString();
    String country = countryElement.getAsString();
    String password = passwordElement.getAsString();
    Integer orgId = orgElement.getAsInt();
    Integer credits = creditsElement.getAsInt();

    Integer roleId = roleElement.getAsInt();
    Integer concurrentExercisesLimit = concurrentExerciseLimitElement.getAsInt();
    Boolean emailVerified = true;//TODO
    Boolean forcePasswordChange = passwordChangeElement.getAsBoolean();

    Integer usrRole = -2;
    switch (roleId) {
    case -1:
        usrRole = Constants.ROLE_RTF_ADMIN;
        break;
    case 0:
        usrRole = Constants.ROLE_ADMIN;
        break;
    case 1:
        usrRole = Constants.ROLE_REVIEWER;
        break;
    case 3:
        usrRole = Constants.ROLE_TEAM_MANAGER;
        break;
    case 4:
        usrRole = Constants.ROLE_STATS;
        break;
    case 7:
        usrRole = Constants.ROLE_USER;
        break;

    default: {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }
    }
    if (usrRole.intValue() < sessionUser.getRole().intValue()) {
        MessageGenerator.sendErrorMessage("NotAuthorized", response);
        return;
    }
    Organization o = hpc.getOrganizationById(orgId);
    if (null == o) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }
    boolean isManager = false;
    for (Organization organization : sessionUser.getManagedOrganizations()) {
        if (o.getId().equals(organization.getId())) {
            isManager = true;
            break;
        }
    }
    if (!isManager) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }
    List<User> organizationUsers = hpc.getManagementAllUsers(new HashSet<Organization>() {
        {
            add(o);
        }
    });
    if (organizationUsers.size() >= o.getMaxUsers()) {
        MessageGenerator.sendErrorMessage("MaxUserLimit", response);
        return;
    }
    if (!PasswordComplexityUtil.isPasswordComplex(password)) {
        MessageGenerator.sendErrorMessage("WeakPassword", response);
        return;
    }
    User existingUser = hpc.getUserFromUsername(username);
    if (existingUser != null) {
        MessageGenerator.sendErrorMessage("UserExists", response);
        return;
    }
    Country c = hpc.getCountryFromCode(country);
    if (null == c) {
        MessageGenerator.sendErrorMessage("NotFound", response);
        return;
    }
    User user = new User();
    user.setEmail(email);
    user.setLastName(lastName);
    user.setUsername(username);
    user.setFirstName(firstName);
    user.setRole(usrRole);
    String salt = RandomGenerator.getNextSalt();
    String pwd = DigestUtils.sha512Hex(password.concat(salt));
    user.setSalt(salt);
    user.setPassword(pwd);
    user.setStatus(UserStatus.ACTIVE);
    user.setCountry(c);
    user.setScore(0);
    user.setExercisesRun(0);
    user.setEmailVerified(emailVerified);
    user.setForceChangePassword(forcePasswordChange);
    user.setInstanceLimit(concurrentExercisesLimit);
    user.setJoinedDateTime(new Date());
    user.setTeam(null);
    user.setCredits(credits);
    user.setCreatedByUser(sessionUser.getIdUser());
    user.setDefaultOrganization(o);
    if (user.getRole().intValue() < Constants.ROLE_USER) {
        user.setManagedOrganizations(new HashSet() {
            {
                add(o);
            }
        });
    } else {
        user.setManagedOrganizations(null);
    }
    Integer id = hpc.addUser(user);
    if (null != id && id > 0) {
        NotificationsHelper helper = new NotificationsHelper();
        helper.addNewUserAdded(user);
        helper.addWelcomeToRTFNotification(user);
        MessageGenerator.sendSuccessMessage(response);
    } else {
        logger.error("Signup failed at DB-end for email: " + email);
        MessageGenerator.sendErrorMessage("SignupFailed", response);
    }
}

From source file:main.java.utils.Utility.java

public static long sha512Hash(String key) {
    String value = DigestUtils.sha512Hex(key.getBytes());
    BigInteger b = new BigInteger(value, 16);

    return (b.longValue());
}

From source file:co.cask.hydrator.plugin.HasherTest.java

@Test
public void testHasherSHA512() throws Exception {
    Transform<StructuredRecord, StructuredRecord> transform = new Hasher(new Hasher.Config("SHA512", "a,b,e"));
    transform.initialize(null);/*from w  w  w. j  a  v a 2s  . c om*/

    MockEmitter<StructuredRecord> emitter = new MockEmitter<>();
    transform.transform(StructuredRecord.builder(INPUT).set("a", "Field A").set("b", "Field B")
            .set("c", "Field C").set("d", 4).set("e", "Field E").build(), emitter);

    ;
    Assert.assertEquals(5, emitter.getEmitted().get(0).getSchema().getFields().size());
    Assert.assertEquals(DigestUtils.sha512Hex("Field A"), emitter.getEmitted().get(0).get("a"));
    Assert.assertEquals(DigestUtils.sha512Hex("Field B"), emitter.getEmitted().get(0).get("b"));
    Assert.assertEquals("Field C", emitter.getEmitted().get(0).get("c"));
    Assert.assertEquals(4, emitter.getEmitted().get(0).get("d"));
    Assert.assertEquals(DigestUtils.sha512Hex("Field E"), emitter.getEmitted().get(0).get("e"));
}