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.jahia.services.modulemanager.persistence.PersistentBundleInfoBuilder.java

private static DigestInputStream toDigestInputStream(InputStream is) {
    try {/* w w  w .  j  a va2s.  c  o  m*/
        return new DigestInputStream(is, MessageDigest.getInstance("MD5"));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.nifi.scripting.ScriptFactory.java

private byte[] getMD5Hash(String aScriptFileName) throws FileNotFoundException, IOException {
    byte[] messageDigest = null;
    try (FileInputStream fis = new FileInputStream(aScriptFileName);
            DigestInputStream dis = new DigestInputStream(new BufferedInputStream(fis),
                    MessageDigest.getInstance("MD5"))) {

        byte[] bytes = new byte[8192];
        while (dis.read(bytes) != -1) {
            // do nothing...just computing the md5 hash
        }/*from  www  . j av  a2 s.  co m*/
        messageDigest = dis.getMessageDigest().digest();
    } catch (NoSuchAlgorithmException swallow) {
        // MD5 is a legitimate format
    }
    return messageDigest;
}

From source file:org.guvnor.ala.build.maven.util.RepositoryVisitor.java

private void makeTempFile(final File parent, final Path path) throws IOException, NoSuchAlgorithmException {

    final int BUFFER = 2048; //Dangerous stuff here ???
    byte data[] = new byte[BUFFER];

    MessageDigest md = MessageDigest.getInstance("MD5");
    DigestInputStream dis = new DigestInputStream(Files.newInputStream(path), md);
    try (BufferedInputStream origin = new BufferedInputStream(dis, BUFFER)) {
        String resourcePath = path.toString();
        readFile(origin, data, BUFFER);//  ww  w .j  a v a 2s . c o  m
        identityHash.put(resourcePath, getMD5String(dis.getMessageDigest().digest()));
    }

    FileOutputStream output = null;
    dis = new DigestInputStream(Files.newInputStream(path), md);
    try (BufferedInputStream origin = new BufferedInputStream(dis, BUFFER)) {
        String resourcePath = path.toString();
        if (oldIdentityHash != null) {
            //if the key exist in the old map and the hash is different then we need to override the file
            if (oldIdentityHash.containsKey(resourcePath) && oldIdentityHash.get(resourcePath) != null
                    && !oldIdentityHash.get(resourcePath).equals(identityHash.get(resourcePath))) {

                output = writeFile(parent, path, output, origin, data, BUFFER);
                System.out.println("Overriding existing file content : " + resourcePath);
            } else if (!oldIdentityHash.containsKey(resourcePath)) {

                output = writeFile(parent, path, output, origin, data, BUFFER);
            }
        } else {
            output = writeFile(parent, path, output, origin, data, BUFFER);
        }
    } finally {
        if (output != null) {
            output.close();
        }
    }

}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.util.io.FileProtection.java

/**
 * Returns an {@link InputStream} for reading from the specified file and
 * performs validation on the file when the {@code close} method is invoked
 * on the stream.// w ww  .  j a  v a  2s. c  o m
 * 
 * @param file the file to the opened and validated
 * @return an {@code InputStream} for reading from the specified file
 * @throws FileNotFoundException if the specified file does not exist
 */
public static InputStream openInputStream(final File file) throws FileNotFoundException {
    return new DigestInputStream(new FileInputStream(file), createMessageDigest()) {

        @Override
        public void close() throws IOException {
            //finish reading the file contents
            byte[] buffer = new byte[Settings.BUFFER_SIZE];

            while (read(buffer) != -1) {
                //reading the data calculates the checksum, nothing else to
                //do here
            }

            super.close();

            //check digest
            validate(file, getMessageDigest().digest());
        }

    };
}

From source file:com.netflix.hollow.example.consumer.infrastructure.S3BlobRetriever.java

private File downloadFile(String objectName) throws IOException {
    for (int retryCount = 0; retryCount < 3; retryCount++) {
        try {// www .jav  a  2 s  .com
            File tempFile = new File(System.getProperty("java.io.tmpdir"), objectName.replace('/', '-'));

            S3Object s3Object = s3.getObject(bucketName, objectName);

            MessageDigest md = MessageDigest.getInstance("MD5");
            try (InputStream is = new DigestInputStream(s3Object.getObjectContent(), md);
                    OutputStream os = new FileOutputStream(tempFile)) {
                IOUtils.copy(is, os);
            }

            String expectedMD5 = s3Object.getObjectMetadata().getETag();
            String actualMD5 = Base16Lower.encodeAsString(md.digest());

            if (!actualMD5.equals(expectedMD5))
                throw new IOException("MD5 sum did not match expected!");

            return tempFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    throw new IOException("Unable to successfully retrieve stream from S3 after 3 retries");
}

From source file:org.eclipse.jgit.lfs.server.fs.LfsServerTest.java

protected LongObjectId putContent(Path f) throws FileNotFoundException, IOException {
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        LongObjectId id1, id2;/*w w w.  jav a  2  s  .c  om*/
        String hexId1, hexId2;
        try (DigestInputStream in = new DigestInputStream(new BufferedInputStream(Files.newInputStream(f)),
                Constants.newMessageDigest())) {
            InputStreamEntity entity = new InputStreamEntity(in, Files.size(f),
                    ContentType.APPLICATION_OCTET_STREAM);
            id1 = LongObjectIdTestUtils.hash(f);
            hexId1 = id1.name();
            HttpPut request = new HttpPut(server.getURI() + "/lfs/objects/" + hexId1);
            request.setEntity(entity);
            HttpResponse response = client.execute(request);
            checkResponseStatus(response);
            id2 = LongObjectId.fromRaw(in.getMessageDigest().digest());
            hexId2 = id2.name();
            assertEquals(hexId1, hexId2);
        }
        return id1;
    }
}

From source file:org.opencastproject.remotetest.util.Utils.java

public static final String md5(File f) throws IOException {
    byte[] bytes = new byte[1024];
    InputStream is = null;/*w ww.  j a va 2 s  .co  m*/
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        is = new DigestInputStream(new FileInputStream(f), md);
        while ((is.read(bytes)) >= 0) {
        }
        return hex(md.digest());
    } catch (NoSuchAlgorithmException e) {
        throw new IOException("No MD5 algorithm available");
    } finally {
        is.close();
    }
}

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

protected DigestInputStream wrap(InputStream stream) {
    final MessageDigest md5 = getMessageDigest();
    return new DigestInputStream(stream, md5);
}

From source file:org.openintents.safe.CryptoHelper.java

/**
 * @param message/*from   w ww  . j  a v  a  2  s  .co  m*/
 * @return MD5 digest of message in a byte array
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
public static byte[] md5String(String message) {

    byte[] input = message.getBytes();

    MessageDigest hash;
    ByteArrayInputStream bIn = null;
    DigestInputStream dIn = null;

    try {
        hash = MessageDigest.getInstance("MD5");

        bIn = new ByteArrayInputStream(input);
        dIn = new DigestInputStream(bIn, hash);

        for (int i = 0; i < input.length; i++) {
            dIn.read();
        }

    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "md5String(): " + e.toString());
    } catch (IOException e) {
        Log.e(TAG, "md5String(): " + e.toString());
    }

    return dIn.getMessageDigest().digest();
}

From source file:org.zanata.rest.client.FileResourceClientTest.java

private Pair<String, Long> calculateFileHashAndSize(InputStream in) {
    try (CountingInputStream countingStream = new CountingInputStream(in)) {
        MessageDigest md = MessageDigest.getInstance("MD5");
        try (InputStream digestInputStream = new DigestInputStream(countingStream, md)) {
            byte[] buffer = new byte[256];
            while (digestInputStream.read(buffer) > 0) {
                // continue
            }/*w  w  w  .  j ava 2 s . com*/
        }
        String hash = new String(Hex.encodeHex(md.digest()));
        return new ImmutablePair<>(hash, countingStream.getByteCount());
    } catch (NoSuchAlgorithmException | IOException e) {
        throw new RuntimeException(e);
    }
}