Example usage for javax.xml.bind DatatypeConverter printHexBinary

List of usage examples for javax.xml.bind DatatypeConverter printHexBinary

Introduction

In this page you can find the example usage for javax.xml.bind DatatypeConverter printHexBinary.

Prototype

public static String printHexBinary(byte[] val) 

Source Link

Document

Converts an array of bytes into a string.

Usage

From source file:com.dell.asm.asmcore.asmmanager.util.deployment.FilterEnvironment.java

public String hash() {
    ObjectMapper mapper = new ObjectMapper();
    StringBuilder total = new StringBuilder();
    total.append(isMinimalServer());/*from ww  w. j a  v a  2s .co m*/
    total.append(isSDBoot());
    total.append(isAllFlash());
    total.append(isHardwareISCSI());
    total.append(isHyperVUsed());
    total.append(isLocalDiskVSANBoot());
    total.append(isLocalStorageForVSANEnabled());
    total.append(isWindowsOS());
    try {
        if (getRaidConfiguration() != null) {
            total.append(mapper.writeValueAsString(getRaidConfiguration()));
        }
        if (getFCCards() != null) {
            total.append(mapper.writeValueAsString(getFCCards()));
        }
        if (getPortUIMap() != null) {
            total.append(mapper.writeValueAsString(getPortUIMap()));
        }
        if (getTwoByTwoInterfaces() != null) {
            total.append(mapper.writeValueAsString(getTwoByTwoInterfaces()));
        }
        if (getIscsiInterfaces() != null) {
            total.append(mapper.writeValueAsString(getIscsiInterfaces()));
        }
        if (getPartitionedInterfaces() != null) {
            total.append(mapper.writeValueAsString(getPartitionedInterfaces()));
        }
        if (getStaticOSInstallInterfaces() != null) {
            total.append(mapper.writeValueAsString(getStaticOSInstallInterfaces()));
        }
    } catch (JsonProcessingException e) {
        logger.warn("FilterEnvironment hash function failed: ", e);
    }
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        return DatatypeConverter.printHexBinary(md.digest(total.toString().getBytes()));
    } catch (NoSuchAlgorithmException e) {
        return total.toString();
    }
}

From source file:net.opentsdb.tree.Branch.java

/**
 * Converts a branch ID hash to a hex encoded, upper case string with padding
 * @param branch_id The ID to convert/*  ww  w  . j  a va2  s  .c  om*/
 * @return the branch ID as a character hex string
 */
public static String idToString(final byte[] branch_id) {
    return DatatypeConverter.printHexBinary(branch_id);
}

From source file:ru.anr.base.BaseParent.java

/**
 * Hash string with sha256 algorithm/*  ww w .j a v  a 2 s . c o  m*/
 *
 * @param s
 *            The given string
 * @return hashed string
 */
public static String sha256(String s) {

    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(s.getBytes());
        return DatatypeConverter.printHexBinary(md.digest()).toLowerCase();
    } catch (NoSuchAlgorithmException ex) {
        throw new ApplicationException(ex);
    }
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

private String revokeInternal(User revoker, Enrollment enrollment, String reason, boolean genCRL)
        throws RevocationException, InvalidArgumentException {

    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set.");
    }//from w  w  w.ja v  a 2  s  .c  o m

    if (enrollment == null) {
        throw new InvalidArgumentException("revokee enrollment is not set");
    }
    if (revoker == null) {
        throw new InvalidArgumentException("revoker is not set");
    }

    logger.debug(format("revoke revoker: %s, reason: %s, url: %s", revoker.getName(), reason, url));

    try {
        setUpSSL();

        // get cert from to-be-revoked enrollment
        BufferedInputStream pem = new BufferedInputStream(
                new ByteArrayInputStream(enrollment.getCert().getBytes()));
        CertificateFactory certFactory = CertificateFactory
                .getInstance(Config.getConfig().getCertificateFormat());
        X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(pem);

        // get its serial number
        String serial = DatatypeConverter.printHexBinary(certificate.getSerialNumber().toByteArray());

        // get its aki
        // 2.5.29.35 : AuthorityKeyIdentifier
        byte[] extensionValue = certificate.getExtensionValue(Extension.authorityKeyIdentifier.getId());
        ASN1OctetString akiOc = ASN1OctetString.getInstance(extensionValue);
        String aki = DatatypeConverter
                .printHexBinary(AuthorityKeyIdentifier.getInstance(akiOc.getOctets()).getKeyIdentifier());

        // build request body
        RevocationRequest req = new RevocationRequest(caName, null, serial, aki, reason, genCRL);
        String body = req.toJson();

        // send revoke request
        JsonObject resp = httpPost(url + HFCA_REVOKE, body, revoker);
        logger.debug("revoke done");

        if (genCRL) {
            if (resp.isEmpty()) {
                throw new RevocationException("Failed to return CRL, revoke response is empty");
            }
            if (resp.isNull("CRL")) {
                throw new RevocationException("Failed to return CRL");
            }
            return resp.getString("CRL");
        }
        return null;
    } catch (CertificateException e) {
        logger.error("Cannot validate certificate. Error is: " + e.getMessage());
        throw new RevocationException("Error while revoking cert. " + e.getMessage(), e);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new RevocationException("Error while revoking the user. " + e.getMessage(), e);

    }
}

From source file:com.amazonaws.services.kinesis.producer.KinesisProducer.java

private void extractBinaries() {
    synchronized (EXTRACT_BIN_MUTEX) {
        final List<File> watchFiles = new ArrayList<>(2);
        String os = SystemUtils.OS_NAME;
        if (SystemUtils.IS_OS_WINDOWS) {
            os = "windows";
        } else if (SystemUtils.IS_OS_LINUX) {
            os = "linux";
        } else if (SystemUtils.IS_OS_MAC_OSX) {
            os = "osx";
        } else {//w  ww . ja va2 s  .c o m
            throw new RuntimeException("Your operation system is not supported (" + os
                    + "), the KPL only supports Linux, OSX and Windows");
        }

        String root = "amazon-kinesis-producer-native-binaries";
        String tmpDir = config.getTempDirectory();
        if (tmpDir.trim().length() == 0) {
            tmpDir = System.getProperty("java.io.tmpdir");
        }
        tmpDir = Paths.get(tmpDir, root).toString();
        pathToTmpDir = tmpDir;

        String binPath = config.getNativeExecutable();
        if (binPath != null && !binPath.trim().isEmpty()) {
            pathToExecutable = binPath.trim();
            log.warn("Using non-default native binary at " + pathToExecutable);
            pathToLibDir = "";
        } else {
            log.info("Extracting binaries to " + tmpDir);
            try {
                File tmpDirFile = new File(tmpDir);
                if (!tmpDirFile.exists() && !tmpDirFile.mkdirs()) {
                    throw new IOException("Could not create tmp dir " + tmpDir);
                }

                String extension = os.equals("windows") ? ".exe" : "";
                String executableName = "kinesis_producer" + extension;
                byte[] bin = IOUtils.toByteArray(this.getClass().getClassLoader()
                        .getResourceAsStream(root + "/" + os + "/" + executableName));
                MessageDigest md = MessageDigest.getInstance("SHA1");
                String mdHex = DatatypeConverter.printHexBinary(md.digest(bin)).toLowerCase();

                pathToExecutable = Paths.get(pathToTmpDir, "kinesis_producer_" + mdHex + extension).toString();
                File extracted = new File(pathToExecutable);
                watchFiles.add(extracted);
                if (extracted.exists()) {
                    try (FileInputStream fis = new FileInputStream(extracted);
                            FileLock lock = fis.getChannel().lock(0, Long.MAX_VALUE, true)) {
                        boolean contentEqual = false;
                        if (extracted.length() == bin.length) {
                            byte[] existingBin = IOUtils.toByteArray(new FileInputStream(extracted));
                            contentEqual = Arrays.equals(bin, existingBin);
                        }
                        if (!contentEqual) {
                            throw new SecurityException("The contents of the binary "
                                    + extracted.getAbsolutePath() + " is not what it's expected to be.");
                        }
                    }
                } else {
                    try (FileOutputStream fos = new FileOutputStream(extracted);
                            FileLock lock = fos.getChannel().lock()) {
                        IOUtils.write(bin, fos);
                    }
                    extracted.setExecutable(true);
                }

                String certFileName = "b204d74a.0";
                File certFile = new File(pathToTmpDir, certFileName);
                if (!certFile.exists()) {
                    try (FileOutputStream fos = new FileOutputStream(certFile);
                            FileLock lock = fos.getChannel().lock()) {
                        byte[] certs = IOUtils.toByteArray(this.getClass().getClassLoader()
                                .getResourceAsStream("cacerts/" + certFileName));
                        IOUtils.write(certs, fos);
                    }
                }

                watchFiles.add(certFile);
                pathToLibDir = pathToTmpDir;
                FileAgeManager.instance().registerFiles(watchFiles);
            } catch (Exception e) {
                throw new RuntimeException("Could not copy native binaries to temp directory " + tmpDir, e);
            }

        }
    }
}

From source file:com.aurel.track.dbase.HandleHome.java

public static String computeHash(File file) {
    try {//from ww  w.j a va2s  . com
        MessageDigest md = MessageDigest.getInstance("MD5");

        InputStream is = new FileInputStream(file);
        byte[] buffer = new byte[4096]; // To hold file contents

        DigestInputStream dis = new DigestInputStream(is, md);
        while (dis.read(buffer) != -1) {

        }

        byte[] digest = md.digest();

        dis.close();

        String hash = DatatypeConverter.printHexBinary(digest);

        return hash;

    } catch (Exception e) {

    }
    return null;
}

From source file:com.aurel.track.dbase.HandleHome.java

public static String computeHash(URL url) {

    InputStream from = null;//from www. jav  a 2  s .  co m
    String hash = "";

    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        from = url.openStream(); // Create input stream
        byte[] buffer = new byte[4096]; // To hold file contents
        DigestInputStream dis = new DigestInputStream(from, md);
        while (dis.read(buffer) != -1) {

        }

        byte[] digest = md.digest();

        dis.close();
        from.close();

        hash = DatatypeConverter.printHexBinary(digest);

    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }
    // Always close the stream, even if exceptions were thrown
    finally {
        if (from != null)
            try {
                from.close();
            } catch (IOException e) {
            }
    }
    return hash;
}

From source file:org.apache.maven.classpath.munger.validation.JarValidationUtilsTest.java

@Test
public void testSignatureOnSameJar() throws Exception {
    URL orgData = getClassContainerLocationURL(Assert.class);
    assertNotNull("Cannot find source URL", orgData);

    File cpyData = createTempFile(getCurrentTestName(), ".jar");
    try (InputStream input = orgData.openStream()) {
        try (OutputStream output = new FileOutputStream(cpyData)) {
            long cpySize = IOUtils.copyLarge(input, output);
            logger.info("Copy(" + orgData.toExternalForm() + ")[" + cpyData.getAbsolutePath() + "]: " + cpySize
                    + " bytes");
        }/*from w  w  w  .  j  a  v  a  2  s .  c o m*/
    }

    NamedPropertySource expected = JarValidationUtils.createJarSignature(orgData);
    NamedPropertySource actual = JarValidationUtils.createJarSignature(cpyData);
    JarValidationUtils.validateJarSignature(expected, actual);

    if (logger.isDebugEnabled()) {
        for (String name : expected.getAvailableNames()) {
            String digestString = expected.getProperty(name);
            byte[] digestValue = DatatypeConverter.parseBase64Binary(digestString);
            logger.debug("    " + name + ": " + DatatypeConverter.printHexBinary(digestValue));
        }
    }
}

From source file:org.apache.nifi.processors.standard.TestPutSQL.java

private String fixedSizeByteArrayAsHexString(int length) {
    byte[] bBinary = RandomUtils.nextBytes(length);
    return DatatypeConverter.printHexBinary(bBinary);
}

From source file:org.apache.syncope.core.persistence.jpa.content.XMLContentExporter.java

private String getValues(final ResultSet rs, final String columnName, final Integer columnType)
        throws SQLException {

    String res = null;//from   w  w w.  j  a  va 2 s. c  om

    try {
        switch (columnType) {
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            final InputStream is = rs.getBinaryStream(columnName);
            if (is != null) {
                res = DatatypeConverter.printHexBinary(IOUtils.toByteArray(is));
            }
            break;

        case Types.BLOB:
            final Blob blob = rs.getBlob(columnName);
            if (blob != null) {
                res = DatatypeConverter.printHexBinary(IOUtils.toByteArray(blob.getBinaryStream()));
            }
            break;

        case Types.BIT:
        case Types.BOOLEAN:
            if (rs.getBoolean(columnName)) {
                res = "1";
            } else {
                res = "0";
            }
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            final Timestamp timestamp = rs.getTimestamp(columnName);
            if (timestamp != null) {
                res = FormatUtils.format(new Date(timestamp.getTime()));
            }
            break;

        default:
            res = rs.getString(columnName);
        }
    } catch (IOException e) {
        LOG.error("Error retrieving hexadecimal string", e);
    }

    return res;
}