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:io.lavagna.model.CardFullWithCounts.java

private static String hash(CardFullWithCounts cwc) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream daos = new DataOutputStream(baos);

    try {//w  w  w.j  ava 2  s  .  c  om
        // card
        daos.writeChars(Integer.toString(cwc.getId()));

        writeNotNull(daos, cwc.getName());
        writeInts(daos, cwc.getSequence(), cwc.getOrder(), cwc.getColumnId(), cwc.getUserId());
        // end card
        writeNotNull(daos, cwc.creationUser);
        writeNotNull(daos, cwc.creationDate);

        if (cwc.counts != null) {
            for (Map.Entry<String, CardDataCount> count : cwc.counts.entrySet()) {
                writeNotNull(daos, count.getKey());
                CardDataCount dataCount = count.getValue();
                daos.writeChars(Integer.toString(dataCount.getCardId()));
                if (dataCount.getCount() != null) {
                    daos.writeChars(Long.toString(dataCount.getCount().longValue()));
                }
                writeNotNull(daos, dataCount.getType());
            }
        }
        for (LabelAndValue lv : cwc.labels) {
            //
            writeInts(daos, lv.getLabelId(), lv.getLabelProjectId());
            writeNotNull(daos, lv.getLabelName());
            writeInts(daos, lv.getLabelColor());
            writeEnum(daos, lv.getLabelType());
            writeEnum(daos, lv.getLabelDomain());
            //
            writeInts(daos, lv.getLabelValueId(), lv.getLabelValueCardId(), lv.getLabelValueLabelId());
            writeNotNull(daos, lv.getLabelValueUseUniqueIndex());
            writeEnum(daos, lv.getLabelValueType());
            writeNotNull(daos, lv.getLabelValueString());
            writeNotNull(daos, lv.getLabelValueTimestamp());
            writeNotNull(daos, lv.getLabelValueInt());
            writeNotNull(daos, lv.getLabelValueCard());
            writeNotNull(daos, lv.getLabelValueUser());
        }
        daos.flush();

        return DigestUtils.sha256Hex(new ByteArrayInputStream(baos.toByteArray()));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.spectralogic.ds3client.integration.DataIntegrity_Test.java

@Test
public void singleFilePut() throws IOException, URISyntaxException, XmlProcessingException, SignatureException {
    final String bucketName = "single_file_put_test";
    final String book = "beowulf.txt";

    try {// w w  w  .jav  a 2s  . com
        HELPERS.ensureBucketExists(bucketName, envDataPolicyId);

        final Path objPath = ResourceUtils.loadFileResource(Util.RESOURCE_BASE_NAME + book);
        final String digest = DigestUtils.sha256Hex(Files.newInputStream(objPath));
        final Ds3Object obj = new Ds3Object(book, Files.size(objPath));

        final Ds3ClientHelpers.Job putJob = HELPERS.startWriteJob(bucketName, Lists.newArrayList(obj));
        putJob.transfer(new ResourceObjectPutter(Util.RESOURCE_BASE_NAME));

        final Path tempDir = Files.createTempDirectory("ds3_test_");

        final Ds3ClientHelpers.Job getJob = HELPERS.startReadAllJob(bucketName);
        getJob.transfer(new FileObjectGetter(tempDir));

        final String secondDigest = DigestUtils.sha256Hex(Files.newInputStream(tempDir.resolve(book)));
        assertThat(secondDigest, is(equalTo(digest)));
    } finally {
        Util.deleteAllContents(client, bucketName);
    }
}

From source file:io.hops.hopsworks.common.dao.tensorflow.config.TensorBoardProcessMgr.java

/**
 * Start the TensorBoard process//from   w w w  .j  av  a2 s . c om
 * @param project
 * @param user
 * @param hdfsUser
 * @param hdfsLogdir
 * @return
 * @throws IOException
 */
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public TensorBoardDTO startTensorBoard(Project project, Users user, HdfsUsers hdfsUser, String hdfsLogdir)
        throws IOException {

    String prog = settings.getHopsworksDomainDir() + "/bin/tensorboard.sh";
    Process process = null;
    Integer port = 0;
    BigInteger pid = null;
    String tbBasePath = settings.getStagingDir() + Settings.TENSORBOARD_DIRS + File.separator;
    String projectUserUniquePath = project.getName() + "_" + hdfsUser.getName();
    String tbPath = tbBasePath + DigestUtils.sha256Hex(projectUserUniquePath);
    String certsPath = "\"\"";

    File tbDir = new File(tbPath);
    if (tbDir.exists()) {
        for (File file : tbDir.listFiles()) {
            if (file.getName().endsWith(".pid")) {
                String pidContents = com.google.common.io.Files.readFirstLine(file, Charset.defaultCharset());
                try {
                    pid = BigInteger.valueOf(Long.parseLong(pidContents));
                    if (pid != null && ping(pid) == 0) {
                        killTensorBoard(pid);
                    }
                } catch (NumberFormatException nfe) {
                    LOGGER.log(Level.WARNING,
                            "Expected number in pidfile " + file.getAbsolutePath() + " got " + pidContents);
                }
            }
        }
        FileUtils.deleteDirectory(tbDir);
    }
    tbDir.mkdirs();

    DistributedFileSystemOps dfso = dfsService.getDfsOps();
    try {
        certsPath = tbBasePath + DigestUtils.sha256Hex(projectUserUniquePath + "_certs");
        File certsDir = new File(certsPath);
        certsDir.mkdirs();
        HopsUtils.materializeCertificatesForUserCustomDir(project.getName(), user.getUsername(),
                settings.getHdfsTmpCertDir(), dfso, certificateMaterializer, settings, certsPath);
    } catch (IOException ioe) {
        LOGGER.log(Level.SEVERE,
                "Failed in materializing certificates for " + hdfsUser + " in directory " + certsPath, ioe);
        HopsUtils.cleanupCertificatesForUserCustomDir(user.getUsername(), project.getName(),
                settings.getHdfsTmpCertDir(), certificateMaterializer, certsPath, settings);
    } finally {
        if (dfso != null) {
            dfsService.closeDfsClient(dfso);
        }
    }

    String anacondaEnvironmentPath = settings.getAnacondaProjectDir(project.getName());
    int retries = 3;

    while (retries > 0) {

        if (retries == 0) {
            throw new IOException(
                    "Failed to start TensorBoard for project=" + project.getName() + ", user=" + user.getUid());
        }

        // use pidfile to kill any running servers
        port = ThreadLocalRandom.current().nextInt(40000, 59999);

        String[] command = new String[] { "/usr/bin/sudo", prog, "start", hdfsUser.getName(), hdfsLogdir,
                tbPath, port.toString(), anacondaEnvironmentPath, settings.getHadoopVersion(), certsPath,
                settings.getJavaHome() };

        LOGGER.log(Level.INFO, Arrays.toString(command));
        ProcessBuilder pb = new ProcessBuilder(command);

        try {
            // Send both stdout and stderr to the same stream
            pb.redirectErrorStream(true);

            process = pb.start();

            synchronized (pb) {
                try {
                    // Wait until the launcher bash script has finished
                    process.waitFor(20l, TimeUnit.SECONDS);
                } catch (InterruptedException ex) {
                    LOGGER.log(Level.SEVERE, "Woken while waiting for the TensorBoard to start: {0}",
                            ex.getMessage());
                }
            }

            int exitValue = process.exitValue();
            String pidPath = tbPath + File.separator + port + ".pid";
            File pidFile = new File(pidPath);
            // Read the pid for TensorBoard server
            if (pidFile.exists()) {
                String pidContents = com.google.common.io.Files.readFirstLine(pidFile,
                        Charset.defaultCharset());
                pid = BigInteger.valueOf(Long.parseLong(pidContents));
            }
            if (exitValue == 0 && pid != null) {
                int maxWait = 10;
                String logFilePath = tbPath + File.separator + port + ".log";
                File logFile = new File(logFilePath);
                while (maxWait > 0) {
                    String logFileContents = com.google.common.io.Files.readFirstLine(logFile,
                            Charset.defaultCharset());
                    // It is not possible to have a fixed wait time before showing the TB, we need to be sure it has started
                    if (logFile.length() > 0
                            && (logFileContents.contains("Loaded") | logFileContents.contains("Reloader")
                                    | logFileContents.contains("event")) | maxWait == 1) {
                        Thread.currentThread().sleep(5000);
                        TensorBoardDTO tensorBoardDTO = new TensorBoardDTO();
                        String host = null;
                        try {
                            host = InetAddress.getLocalHost().getHostAddress();
                        } catch (UnknownHostException ex) {
                            Logger.getLogger(TensorBoardProcessMgr.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        tensorBoardDTO.setEndpoint(host + ":" + port);
                        tensorBoardDTO.setPid(pid);
                        return tensorBoardDTO;
                    } else {
                        Thread.currentThread().sleep(1000);
                        maxWait--;
                    }
                }
                TensorBoardDTO tensorBoardDTO = new TensorBoardDTO();
                tensorBoardDTO.setPid(pid);
                String host = null;
                try {
                    host = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException ex) {
                    Logger.getLogger(TensorBoardProcessMgr.class.getName()).log(Level.SEVERE, null, ex);
                }
                tensorBoardDTO.setEndpoint(host + ":" + port);
                return tensorBoardDTO;
            } else {
                LOGGER.log(Level.SEVERE,
                        "Failed starting TensorBoard got exitcode " + exitValue + " retrying on new port");
                if (pid != null) {
                    this.killTensorBoard(pid);
                }
                pid = null;
            }

        } catch (Exception ex) {
            LOGGER.log(Level.SEVERE, "Problem starting TensorBoard: {0}", ex);
            if (process != null) {
                process.destroyForcibly();
            }
        } finally {
            retries--;
        }
    }

    //Failed to start TensorBoard, make sure there is no process running for it! (This should not be needed)
    if (pid != null && this.ping(pid) == 0) {
        this.killTensorBoard(pid);
    }

    //Certificates cleanup in case they were materialized but no TB started successfully

    dfso = dfsService.getDfsOps();
    certsPath = tbBasePath + DigestUtils.sha256Hex(projectUserUniquePath + "_certs");
    File certsDir = new File(certsPath);
    certsDir.mkdirs();
    try {
        HopsUtils.cleanupCertificatesForUserCustomDir(user.getUsername(), project.getName(),
                settings.getHdfsTmpCertDir(), certificateMaterializer, certsPath, settings);
    } finally {
        if (dfso != null) {
            dfsService.closeDfsClient(dfso);
        }
    }

    return null;
}

From source file:it.greenvulcano.script.impl.ScriptExecutorImpl.java

/**
 * Initialize the instance.//  w w w . ja v  a  2  s .  co  m
 * 
 * @param node
 *        the configuration node
 * @throws GVScriptException
 */
public void init(Node node) throws GVScriptException {
    try {
        name = XMLConfig.get(node.getParentNode(), "@name");
        logger.debug("init script node " + name);
        lang = XMLConfig.get(node, "@lang", "js");
        String file = XMLConfig.get(node, "@file", "");
        if (!"".equals(file)) {
            scriptName = file;
            script = cache.getScript(file);
        } else {
            scriptName = ScriptCache.INTERNAL_SCRIPT;
            script = XMLConfig.get(node, ".", null);
        }

        if ((script == null) || "".equals(script)) {
            throw new GVScriptException("Empty configured script!");
        }

        ScriptEngine engine = getScriptEngine(lang);
        if (engine == null) {
            throw new GVScriptException("ScriptEngine[" + lang + "] not found!");
        }

        String bcName = XMLConfig.get(node, "@base-context", null);
        String baseContext = BaseContextManager.instance().getBaseContextScript(lang, bcName);
        if (baseContext != null) {
            script = baseContext + "\n\n" + (script != null ? script : "");
        } else if (bcName != null) {
            throw new GVScriptException("BaseContext[" + lang + "/" + bcName + "] not found!");
        }

        if (engine instanceof Compilable && PropertiesHandler.isExpanded(script)) {
            String scriptKey = DigestUtils.sha256Hex(script);

            Optional<CompiledScript> cachedCompiledScript = cache.getCompiledScript(scriptKey);

            if (cachedCompiledScript.isPresent()) {
                compScript = cachedCompiledScript.get();
            } else {
                logger.debug("Static script[" + lang + "], can be compiled for performance");
                compScript = ((Compilable) engine).compile(script);
                cache.putCompiledScript(scriptKey, compScript);
            }
        }
        bindings = engine.createBindings();

        initialized = true;
    } catch (GVScriptException exc) {
        logger.error("Error initializing ScriptExecutorImpl", exc);
        throw exc;
    } catch (Exception exc) {
        logger.error("Error initializing ScriptExecutorImpl", exc);
        throw new GVScriptException("Error initializing ScriptExecutorImpl", exc);
    }
}

From source file:com.qwazr.connectors.TableRealmConnector.java

@Override
public Account verify(String id, Credential credential) {

    // This realm only support one type of credential
    if (!(credential instanceof PasswordCredential))
        throw new RuntimeException("Unsupported credential type: " + credential.getClass().getName());

    PasswordCredential passwordCredential = (PasswordCredential) credential;

    // We request the database
    final LinkedHashMap<String, Object> row;
    try {//from ww w .  jav  a 2  s. com
        row = tableService.getRow(table_name, id, columns);
        if (row == null)
            return null;
    } catch (WebApplicationException e) {
        if (e.getResponse().getStatusInfo().getFamily() == Response.Status.Family.CLIENT_ERROR)
            return authenticationFailure("Unknown user: " + id);
        throw e;
    }

    Object password = row.get(password_column);
    if (password == null)
        return null;
    if (password instanceof String[]) {
        String[] passwordArray = (String[]) password;
        if (passwordArray.length == 0)
            return null;
        password = passwordArray[0];
    }

    // The password is stored hashed
    final String passwd = new String(passwordCredential.getPassword());
    String digest = DigestUtils.sha256Hex(passwd);
    if (!digest.equals(password))
        return authenticationFailure("Wrong password: " + id + " " + digest + '/' + passwd + '/' + password);

    //We retrieve the roles
    Object object = row.get(roles_column);
    LinkedHashSet<String> roles = new LinkedHashSet<String>();
    if (object instanceof String[]) {
        for (Object o : (String[]) object)
            roles.add(o.toString());
    } else
        roles.add(object.toString());

    return new Account() {
        @Override
        public Principal getPrincipal() {
            return new Principal() {
                @Override
                public String getName() {
                    return id;
                }
            };
        }

        @Override
        public Set<String> getRoles() {
            return roles;
        }
    };
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java

/**
 * Get SHA256 fingerprint/thumbprint of a Certificate
 * Returns the fingerprint as a colon delimited hex string
 *
 * @param cert Certificate//from www. j a  v  a  2s .co  m
 * @return Hex encoded sha256 fingerprint of certificate
 * @throws CertificateException
 */
public String getSha256Fingerprint(Certificate cert) throws CertificateException {
    byte[] encoded = cert.getEncoded();
    String certFinger = DigestUtils.sha256Hex(encoded);
    return fixFingerprintHex(certFinger);
}

From source file:it.greenvulcano.gvesb.gviamx.service.internal.PasswordResetManager.java

public void createPasswordResetRequest(String email) throws UserNotFoundException, UnverifiableUserException {

    User user = usersManager.getUser(email.toLowerCase());

    if (user.getPassword().isPresent()) {

        PasswordResetRequest passwordResetRequest = repository
                .get(email.toLowerCase(), PasswordResetRequest.class).orElseGet(PasswordResetRequest::new);
        passwordResetRequest.setUser((UserJPA) user);
        passwordResetRequest.setEmail(email.toLowerCase());
        passwordResetRequest.setIssueTime(new Date());
        passwordResetRequest.setExpireTime(expireTime);
        passwordResetRequest.setNotificationStatus(NotificationStatus.PENDING);

        byte[] token = new byte[4];
        secureRandom.nextBytes(token);/*from w ww.j av a 2s.c o m*/

        String clearTextToken = String.format(Locale.US, "%02x%02x%02x%02x",
                IntStream.range(0, token.length).mapToObj(i -> Byte.valueOf(token[i])).toArray());
        passwordResetRequest.setToken(DigestUtils.sha256Hex(clearTextToken));

        repository.add(passwordResetRequest);

        passwordResetRequest.setClearToken(clearTextToken);
        notificationServices.stream().map(
                n -> new NotificationManager.NotificationTask(n, passwordResetRequest, repository, "reset"))
                .forEach(executor::submit);

    } else {
        throw new UnverifiableUserException(email);
    }
}

From source file:me.vertretungsplan.parser.LegionBoardParser.java

/**
 * Returns authentication key as shown/* w w w  . j av  a 2 s  .c  o  m*/
 * <a href="https://gitlab.com/legionboard/heart/blob/master/doc/README.md">in the documentation</a>.
 */
private String getAuthenticationKey(Credential credential) {
    final UserPasswordCredential userPasswordCredential = (UserPasswordCredential) credential;
    final String username = userPasswordCredential.getUsername();
    final String password = userPasswordCredential.getPassword();
    return DigestUtils.sha256Hex(username.toLowerCase() + "//" + password);
}

From source file:com.squid.kraken.v4.caching.redis.RedisCacheManagerMock.java

public String buildCacheKey(String SQLQuery, List<String> dependencies) {
    String key = "";
    if (dependencies.size() > 0) {
        key += dependencies.get(0);//from   w  w w . j  a v a2s .  co  m
    }
    key += "-" + DigestUtils.sha256Hex(SQLQuery);
    //
    RedisKey rk = getKey(key, dependencies);
    return rk.getStringKey();

}

From source file:com.remediatetheflag.global.actions.unauth.DoLoginAction.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 passwordElement = json.get(Constants.ACTION_PARAM_PASSWORD);
    String password = passwordElement.getAsString();

    if (null == username || username.equals("") || null == password || password.equals("")) {
        MessageGenerator.sendRedirectMessage(Constants.INDEX_PAGE, response);
        return;//from   ww  w  . j a  v a 2s. c om
    }
    Integer failedAttempts = hpc.getFailedLoginAttemptsForUser(username);
    if (failedAttempts >= Constants.FAILED_ATTEMPTS_LOCKOUT) {
        logger.warn("Username " + username + " is locked out, login refused");
        MessageGenerator.sendErrorMessage(Constants.JSON_VALUE_ERROR_ACCOUNT_LOCKOUT, response);
        User lockedUser = hpc.getUserFromUsername(username);
        if (null != lockedUser) {
            lockedUser.setStatus(UserStatus.LOCKED);
            hpc.updateUserInfo(lockedUser);
        }
        MessageGenerator.sendRedirectMessage(Constants.INDEX_PAGE, response);
        return;
    }

    User user = hpc.getUser(username, password);

    UserAuthenticationEvent attempt = new UserAuthenticationEvent();
    attempt.setUsername(username);

    if (null != user && user.getUsername() != null) {
        if (!user.getStatus().equals(UserStatus.ACTIVE)) {
            logger.warn("Login UNSUCCESSFUL for USER: " + username + " - USER IS: " + user.getStatus());
            MessageGenerator.sendRedirectMessage(Constants.INDEX_PAGE, response);
            return;
        }
        request.getSession().invalidate();
        request.getSession(true);
        request.getSession().setAttribute(Constants.ATTRIBUTE_SECURITY_CONTEXT, user);
        request.getSession().setAttribute(Constants.ATTRIBUTE_SECURITY_ROLE, user.getRole());
        CSRFTokenUtils.setToken(request.getSession());
        if (user.getRole() <= Constants.ROLE_STATS) {
            logger.debug("Login successful for ADMIN: " + user.getUsername());
            MessageGenerator.sendRedirectMessage(Constants.MGMT_HOME, response);
        } else {
            logger.debug("Login successful for USER: " + user.getUsername());
            MessageGenerator.sendRedirectMessage(Constants.USER_HOME, response);
        }
        hpc.setFailedLoginAttemptsForUser(username, 0);
        user.setLastLogin(new Date());
        hpc.updateUserInfo(user);
        attempt.setSessionIdHash(DigestUtils.sha256Hex(request.getSession().getId()));
        attempt.setLoginSuccessful(true);
        attempt.setLoginDate(new Date());
        hpc.addLoginEvent(attempt);
    } else {
        failedAttempts++;
        hpc.setFailedLoginAttemptsForUser(username, failedAttempts);
        attempt.setLoginSuccessful(false);
        attempt.setLoginDate(new Date());
        hpc.addLoginEvent(attempt);
        logger.warn("Login UNSUCCESSFUL for USER: " + username);
        MessageGenerator.sendRedirectMessage(Constants.INDEX_PAGE, response);
    }
}