Example usage for java.security DigestInputStream read

List of usage examples for java.security DigestInputStream read

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

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

/**
 * Generates the MD5 hash of the file provided
 * @param file/* w w  w.j  a v a2  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:io.amient.yarn1.YarnClient.java

/**
 * Distribute all dependencies in a single jar both from Client to Master as well as Master to Container(s)
 *//*from ww  w .  j av  a 2s  .c  o  m*/
public static void distributeResources(Configuration yarnConf, Properties appConf, String appName)
        throws IOException {
    final FileSystem distFs = FileSystem.get(yarnConf);
    final FileSystem localFs = FileSystem.getLocal(yarnConf);
    try {

        //distribute configuration
        final Path dstConfig = new Path(distFs.getHomeDirectory(), appName + ".configuration");
        final FSDataOutputStream fs = distFs.create(dstConfig);
        appConf.store(fs, "Yarn1 Application Config for " + appName);
        fs.close();
        log.info("Updated resource " + dstConfig);

        //distribute main jar
        final String localPath = YarnClient.class.getProtectionDomain().getCodeSource().getLocation().getFile()
                .replace(".jar/", ".jar");
        final Path src;
        final String jarName = appName + ".jar";
        if (localPath.endsWith(".jar")) {
            log.info("Distributing local jar : " + localPath);
            src = new Path(localPath);
        } else {
            try {
                String localArchive = localPath + appName + ".jar";
                localFs.delete(new Path(localArchive), false);
                log.info("Unpacking compile scope dependencies: " + localPath);
                executeShell("mvn -f " + localPath + "/../.. generate-resources");
                log.info("Preparing application main jar " + localArchive);
                executeShell("jar cMf " + localArchive + " -C " + localPath + " ./");
                src = new Path(localArchive);

            } catch (InterruptedException e) {
                throw new IOException(e);
            }
        }

        byte[] digest;
        final MessageDigest md = MessageDigest.getInstance("MD5");
        try (InputStream is = new FileInputStream(src.toString())) {
            DigestInputStream dis = new DigestInputStream(is, md);
            byte[] buffer = new byte[8192];
            int numOfBytesRead;
            while ((numOfBytesRead = dis.read(buffer)) > 0) {
                md.update(buffer, 0, numOfBytesRead);
            }
            digest = md.digest();
        }
        log.info("Local check sum: " + Hex.encodeHexString(digest));

        final Path dst = new Path(distFs.getHomeDirectory(), jarName);
        Path remoteChecksumFile = new Path(distFs.getHomeDirectory(), jarName + ".md5");
        boolean checksumMatches = false;
        if (distFs.isFile(remoteChecksumFile)) {
            try (InputStream r = distFs.open(remoteChecksumFile)) {
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                int nRead;
                byte[] data = new byte[1024];
                while ((nRead = r.read(data, 0, data.length)) != -1) {
                    buffer.write(data, 0, nRead);
                }
                buffer.flush();
                byte[] remoteDigest = buffer.toByteArray();
                log.info("Remote check sum: " + Hex.encodeHexString(remoteDigest));
                checksumMatches = Arrays.equals(digest, remoteDigest);

            }
        }
        if (!checksumMatches) {
            log.info("Updating resource " + dst + " ...");
            distFs.copyFromLocalFile(false, true, src, dst);
            try (FSDataOutputStream remoteChecksumStream = distFs.create(remoteChecksumFile)) {
                log.info("Updating checksum " + remoteChecksumFile + " ...");
                remoteChecksumStream.write(digest);
            }
            FileStatus scFileStatus = distFs.getFileStatus(dst);
            log.info("Updated resource " + dst + " " + scFileStatus.getLen());
        }
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }
}

From source file:Manifest.java

/**
 * This convenience method is used by both create() and verify(). It reads
 * the contents of a named file and computes a message digest for it, using
 * the specified MessageDigest object.//www .j av  a2  s  . c  o m
 */
public static byte[] getFileDigest(String filename, MessageDigest md) throws IOException {
    // Make sure there is nothing left behind in the MessageDigest
    md.reset();

    // Create a stream to read from the file and compute the digest
    DigestInputStream in = new DigestInputStream(new FileInputStream(filename), md);

    // Read to the end of the file, discarding everything we read.
    // The DigestInputStream automatically passes all the bytes read to
    // the update() method of the MessageDigest
    while (in.read(buffer) != -1)
        /* do nothing */;

    // Finally, compute and return the digest value.
    return md.digest();
}

From source file:fr.gouv.culture.vitam.digest.DigestCompute.java

/**
 * // w  ww.  j a v a2s .c  o  m
 * @param fis
 * @param algorithm
 * @return the Hashcode according to the algorithm
 * @throws Exception
 */
public final static String getHashCode(FileInputStream fis, String algorithm) throws Exception {
    MessageDigest md = MessageDigest.getInstance(algorithm);
    DigestInputStream dis = null;
    try {
        dis = new DigestInputStream(fis, md);
        byte[] buffer = new byte[8192];
        while (dis.read(buffer) != -1)
            ;
    } finally {
        if (dis != null) {
            dis.close();
        }
    }
    byte[] bDigest = md.digest();
    return Base64.encode(bDigest, false);
}

From source file:hudson.Util.java

/**
 * Computes MD5 digest of the given input stream.
 *
 * @param source/*from   ww  w .j a  v  a2  s  .co m*/
 *      The stream will be closed by this method at the end of this method.
 * @return
 *      32-char wide string
 */
public static String getDigestOf(InputStream source) throws IOException {
    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");

        DigestInputStream in = new DigestInputStream(source, md5);
        try {
            while (in.read(garbage) > 0)
                ; // simply discard the input
        } finally {
            in.close();
        }
        return toHexString(md5.digest());
    } catch (NoSuchAlgorithmException e) {
        throw new IOException2("MD5 not installed", e); // impossible
    }
}

From source file:me.lachlanap.summis.downloader.VerifierCallable.java

@Override
public Void call() throws Exception {
    Path file = binaryRoot.resolve(info.getName());
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
    byte[] buffer = new byte[1024];
    try (final InputStream is = Files.newInputStream(file)) {
        DigestInputStream dis = new DigestInputStream(new DigestInputStream(is, md5), sha1);
        while (dis.read(buffer) != -1) {
            ;//from   w  w  w  .j  a v a 2 s  . com
        }
    }
    String md5Digest = new String(Hex.encodeHex(md5.digest()));
    String sha1Digest = new String(Hex.encodeHex(sha1.digest()));
    if (!md5Digest.equals(info.getMD5Digest()) || !sha1Digest.equals(info.getSHA1Digest()))
        throw new RuntimeException(info.getName() + " failed verification");
    downloadListener.completedAVerify();
    return null;
}

From source file:info.magnolia.module.files.MD5CheckingFileExtractorOperation.java

/**
 * Completely reads an InputStream and returns its MD5.
 * TODO : should we close it?//  ww  w .java2 s . c om
 */
protected String calculateMD5(InputStream stream) throws IOException {
    final DigestInputStream md5Stream = wrap(stream);
    byte[] buffer = new byte[1024];
    while (md5Stream.read(buffer) != -1) {
    }

    return retrieveMD5(md5Stream);
}

From source file:hudson.Util.java

/**
 * Computes MD5 digest of the given input stream.
 *
 * @param source//w w w  . j a v  a  2  s  . co  m
 *      The stream will be closed by this method at the end of this method.
 * @return
 *      32-char wide string
 */
public static String getDigestOf(InputStream source) throws IOException {
    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");

        byte[] buffer = new byte[1024];
        DigestInputStream in = new DigestInputStream(source, md5);
        try {
            while (in.read(buffer) > 0)
                ; // simply discard the input
        } finally {
            in.close();
        }
        return toHexString(md5.digest());
    } catch (NoSuchAlgorithmException e) {
        throw new IOException2("MD5 not installed", e); // impossible
    }
}

From source file:org.wso2.carbon.connector.amazons3.auth.AmazonS3ContentMD5Builder.java

/**
 * Consume the string type delete configuration and returns its Base-64 encoded MD5 checksum as a string.
 *
 * @param deleteConfig gets delete configuration as a string.
 * @return String type base-64 encoded MD5 checksum.
 * @throws IOException                    if an I/O error occurs when reading bytes of data from input stream.
 * @throws NoSuchAlgorithmException if no implementation for the specified algorithm.
 */// ww  w.  j av a2  s . c o m
private String getContentMD5Header(final String deleteConfig) throws IOException, NoSuchAlgorithmException {

    String contentHeader = null;
    // convert String into InputStream
    final InputStream inputStream = new ByteArrayInputStream(deleteConfig.getBytes(Charset.defaultCharset()));
    final DigestInputStream digestInputStream = new DigestInputStream(inputStream,
            MessageDigest.getInstance(AmazonS3Constants.MD5));

    final byte[] buffer = new byte[AmazonS3Constants.BUFFER_SIZE];
    while (digestInputStream.read(buffer) > 0) {
        contentHeader = new String(Base64.encodeBase64(digestInputStream.getMessageDigest().digest()),
                Charset.defaultCharset());
    }
    return contentHeader;
}

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

public static String computeHash(File file) {
    try {//from www.  j av a  2 s  .  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;
}