Example usage for java.security DigestInputStream DigestInputStream

List of usage examples for java.security DigestInputStream DigestInputStream

Introduction

In this page you can find the example usage for java.security DigestInputStream DigestInputStream.

Prototype

public DigestInputStream(InputStream stream, MessageDigest digest) 

Source Link

Document

Creates a digest input stream, using the specified input stream and message digest.

Usage

From source file:org.springframework.integration.aws.core.AWSCommonUtils.java

/**
 * Generates the MD5 hash of the file provided
 * @param file/*from  w  w w  .  j  a v a 2  s  .  co m*/
 */
public static byte[] getContentsMD5AsBytes(File file) {

    DigestInputStream din = null;
    final byte[] digestToReturn;

    try {
        BufferedInputStream bin = new BufferedInputStream(new FileInputStream(file), 32768);
        din = new DigestInputStream(bin, MessageDigest.getInstance("MD5"));
        //Just to update the digest
        byte[] dummy = new byte[4096];
        for (int i = 1; i > 0; i = din.read(dummy))
            ;
        digestToReturn = din.getMessageDigest().digest();
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Caught Exception while generating a MessageDigest instance", e);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException("File " + file.getName() + " not found", e);
    } catch (IOException e) {
        throw new IllegalStateException("Caught exception while reading from file", e);
    } finally {
        IOUtils.closeQuietly(din);
    }
    return digestToReturn;
}

From source file:rapture.plugin.install.PluginContentReader.java

public static byte[] readFromFile(File file, MessageDigest md) throws IOException {
    DigestInputStream is;/*from  w  w w .  j  ava2s  .co m*/

    try {
        is = new DigestInputStream(new FileInputStream(file), md);
    } catch (FileNotFoundException e) {
        String path = file.getPath();
        if (path.endsWith(".bits")) {
            File f = new File(path.substring(0, path.length() - 5));
            is = new DigestInputStream(new FileInputStream(f), md);
        } else {
            throw e;
        }
    }

    return readFromStream(is);
}

From source file:Main.java

public static String md5(InputStream in) {
    int bufferSize = 256 * 1024;
    DigestInputStream digestInputStream = null;
    try {//from w ww. ja v a2s .  c  o m
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        digestInputStream = new DigestInputStream(in, messageDigest);
        byte[] buffer = new byte[bufferSize];
        while (digestInputStream.read(buffer) > 0)
            ;
        messageDigest = digestInputStream.getMessageDigest();
        byte[] resultByteArray = messageDigest.digest();
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        char[] resultCharArray = new char[resultByteArray.length * 2];
        int index = 0;
        for (byte b : resultByteArray) {
            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }
        return new String(resultCharArray);
    } catch (NoSuchAlgorithmException e) {
        return null;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (digestInputStream != null)
                digestInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:hadoopInstaller.io.MD5Calculator.java

/**
 * /*from w  ww .j  av  a  2 s . c o  m*/
 * @param file
 *            the file object to calculate md5 for. (single file, not
 *            folder)
 * @return a string with the calculated md5 in lowercase.
 * @throws NoSuchAlgorithmException
 * @throws {@link
 *             FileSystemException}
 * @throws IOException
 */
public static String calculateFor(FileObject file) throws NoSuchAlgorithmException, IOException {
    try (InputStream is = file.getContent().getInputStream();
            DigestInputStream dis = new DigestInputStream(is, MessageDigest.getInstance("MD5"));) { //$NON-NLS-1$
        byte[] in = new byte[1024];
        while ((dis.read(in)) > 0) {
            // Read until there's nothing left.
        }
        return javax.xml.bind.DatatypeConverter.printHexBinary(dis.getMessageDigest().digest()).toLowerCase();
    }
}

From source file:Main.java

public static String encode(InputStream in) {
    int bufferSize = 256 * 1024;
    DigestInputStream digestInputStream = null;
    try {//  w  ww .j a va  2 s.com
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        digestInputStream = new DigestInputStream(in, messageDigest);
        byte[] buffer = new byte[bufferSize];
        while (digestInputStream.read(buffer) > 0)
            ;
        messageDigest = digestInputStream.getMessageDigest();
        byte[] resultByteArray = messageDigest.digest();
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        char[] resultCharArray = new char[resultByteArray.length * 2];
        int index = 0;
        for (byte b : resultByteArray) {
            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }
        return new String(resultCharArray);
    } catch (NoSuchAlgorithmException e) {
        return null;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (digestInputStream != null)
                digestInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:acmi.l2.clientmod.l2_version_switcher.Util.java

public static boolean hashEquals(File file, String hashString) throws IOException {
    try {/*from  w  ww .j  av  a2 s  . co m*/
        MessageDigest md = MessageDigest.getInstance("sha-1");
        try (FileInputStream hashBytes = new FileInputStream(file)) {
            DigestInputStream dis = new DigestInputStream(hashBytes, md);
            IOUtils.copy(dis, NullOutputStream.NULL_OUTPUT_STREAM);
        }
        byte[] hash = md.digest();
        return Arrays.equals(hash, parseHexBinary(hashString));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:nl.knaw.dans.easy.sword2examples.ContinuedDeposit.java

public static URI depositPackage(File bagDir, IRI colIri, String uid, String pw, int chunkSize)
        throws Exception {
    // 0. Zip the bagDir
    File zipFile = new File(bagDir.getAbsolutePath() + ".zip");
    zipFile.delete();/*from  w  ww . j ava2  s .c  o  m*/
    Common.zipDirectory(bagDir, zipFile);

    // 1. Set up stream for calculating MD5
    FileInputStream fis = new FileInputStream(zipFile);
    MessageDigest md = MessageDigest.getInstance("MD5");
    DigestInputStream dis = new DigestInputStream(fis, md);

    // 2. Post first chunk bag to Col-IRI
    CloseableHttpClient http = Common.createHttpClient(colIri.toURI(), uid, pw);
    CloseableHttpResponse response = Common.sendChunk(dis, chunkSize, "POST", colIri.toURI(), "bag.zip.1",
            "application/octet-stream", http, chunkSize < zipFile.length());

    // 3. Check the response. If transfer corrupt (MD5 doesn't check out), report and exit.
    String bodyText = Common.readEntityAsString(response.getEntity());
    if (response.getStatusLine().getStatusCode() != 201) {
        System.err.println("FAILED. Status = " + response.getStatusLine());
        System.err.println("Response body follows:");
        System.err.println(bodyText);
        System.exit(2);
    }
    System.out.println("SUCCESS. Deposit receipt follows:");
    System.out.println(bodyText);

    Entry receipt = Common.parse(bodyText);
    Link seIriLink = receipt.getLink("edit");
    URI seIri = seIriLink.getHref().toURI();

    int remaining = (int) zipFile.length() - chunkSize;
    int count = 2;
    while (remaining > 0) {
        System.out.print(String.format("POST-ing chunk of %d bytes to SE-IRI (remaining: %d) ... ", chunkSize,
                remaining));
        response = Common.sendChunk(dis, chunkSize, "POST", seIri, "bag.zip." + count++,
                "application/octet-stream", http, remaining > chunkSize);
        remaining -= chunkSize;
        bodyText = Common.readEntityAsString(response.getEntity());
        if (response.getStatusLine().getStatusCode() != 200) {
            System.err.println("FAILED. Status = " + response.getStatusLine());
            System.err.println("Response body follows:");
            System.err.println(bodyText);
            System.exit(2);
        }
        System.out.println("SUCCESS.");
    }

    // 4. Get the statement URL. This is the URL from which to retrieve the current status of the deposit.
    System.out.println("Retrieving Statement IRI (Stat-IRI) from deposit receipt ...");
    receipt = Common.parse(bodyText);
    Link statIriLink = receipt.getLink("http://purl.org/net/sword/terms/statement");
    IRI statIri = statIriLink.getHref();
    System.out.println("Stat-IRI = " + statIri);

    // 5. Check statement every ten seconds (a bit too frantic, but okay for this test). If status changes:
    // report new status. If status is an error (INVALID, REJECTED, FAILED) or ARCHIVED: exit.
    return Common.trackDeposit(http, statIri.toURI());
}

From source file:rapture.plugin.install.PluginContentReader.java

public static byte[] readFromStreamWithDigest(InputStream is, MessageDigest md) throws IOException {
    DigestInputStream dis = new DigestInputStream(is, md);

    return readFromStream(dis);

}

From source file:org.fcrepo.kernel.impl.utils.FixityInputStream.java

/**
 * Creates a <code>FilterInputStream</code> by assigning the
 * argument <code>in</code> to the field <code>this.in</code>
 * so as to remember it for later use.//www.j  a va 2  s . c  o m
 *
 * @param in the underlying input stream, or <code>null</code> if
 *           this instance is to be created without an underlying stream.
 * @param digest the given digest
 */
public FixityInputStream(final InputStream in, final MessageDigest digest) {
    super(new DigestInputStream(in, digest));
}

From source file:com.thoughtworks.go.agent.launcher.DownloadableFile.java

protected static boolean matchChecksum(File localFile, String expectedSignature) {
    try (FileInputStream input = new FileInputStream(localFile)) {
        MessageDigest digester = MessageDigest.getInstance("MD5");
        try (DigestInputStream digest = new DigestInputStream(input, digester)) {
            IOUtils.copy(digest, new NullOutputStream());
        }/*from  w w w .  j av  a2s  .  c  o  m*/
        return expectedSignature.equalsIgnoreCase(encodeHexString(digester.digest()));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}