Example usage for java.security DigestInputStream getMessageDigest

List of usage examples for java.security DigestInputStream getMessageDigest

Introduction

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

Prototype

public MessageDigest getMessageDigest() 

Source Link

Document

Returns the message digest associated with this stream.

Usage

From source file:org.eclipse.hawkbit.artifact.repository.ArtifactStoreTest.java

@Test
@Description("Ensures that search by SHA1 hash (which is used by hawkBit as artifact ID) finds the expected results.")
public void findArtifactBySHA1Hash() throws NoSuchAlgorithmException {
    final int filelengthBytes = 128;
    final String filename = "testfile.json";
    final String contentType = "application/json";

    final DigestInputStream digestInputStream = digestInputStream(generateInputStream(filelengthBytes),
            "SHA-1");
    artifactStoreUnderTest.store(digestInputStream, filename, contentType);
    assertThat(artifactStoreUnderTest.getArtifactBySha1(
            BaseEncoding.base16().lowerCase().encode(digestInputStream.getMessageDigest().digest())))
                    .isNotNull();/*from  w  ww . j  a v  a  2 s. c  o  m*/
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.DatasetFactory.java

private String getDigest(Path aFile, String aDigest) throws IOException {
    MessageDigest digest;//from   w w  w.  ja  v a2  s .c om
    try {
        digest = MessageDigest.getInstance(aDigest);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }
    try (InputStream is = Files.newInputStream(aFile)) {
        DigestInputStream digestFilter = new DigestInputStream(is, digest);
        IOUtils.copy(digestFilter, new NullOutputStream());
        return new String(Hex.encodeHex(digestFilter.getMessageDigest().digest()));
    }
}

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

/**
 * @param message//from w  w  w  .j ava 2 s.  c o  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.seadva.dataone.DataOneUtil.java

@GET
@Path("addObject")
@Produces(MediaType.APPLICATION_JSON)//from   w  w w  . j ava2s  .  c om
public String addObject(@QueryParam("filePath") String filePath, @QueryParam("id") String identifier,
        @QueryParam("schema") String metaFormat) throws IndexServiceException {

    ResearchObject researchObject = new ResearchObject();

    String filename = ((String) filePath).split("/")[((String) filePath).split("/").length - 1].replace(".xml",
            "");
    if (metaFormat == null)
        metaFormat = "http://www.fgdc.gov/schemas/metadata/fgdc-std-001-1998.xsd";
    if (identifier == null)
        identifier = filename;

    SeadFile metadataFile = new SeadFile();
    metadataFile.setId(filename);
    metadataFile.setName(filename);
    metadataFile.setSource("file://" + filePath);

    try {
        DigestInputStream digestStream = new DigestInputStream(new FileInputStream(filePath),
                MessageDigest.getInstance("SHA-1"));
        if (digestStream.read() != -1) {
            byte[] buf = new byte[1024];
            while (digestStream.read(buf) != -1)
                ;
        }
        byte[] digest = digestStream.getMessageDigest().digest();
        DcsFixity fixity = new DcsFixity();
        fixity.setAlgorithm("SHA-1");
        fixity.setValue(new String(Hex.encodeHex(digest)));
        metadataFile.addFixity(fixity);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    DcsFormat metadataFormat = new DcsFormat();
    metadataFormat.setFormat(metaFormat);
    metadataFile.addFormat(metadataFormat);

    DcsResourceIdentifier dcsResourceIdentifier = new DcsResourceIdentifier();
    dcsResourceIdentifier.setIdValue(identifier);
    dcsResourceIdentifier.setTypeId("dataone");
    metadataFile.addAlternateId(dcsResourceIdentifier);

    File metaFile = new File(filePath);
    metadataFile.setSizeBytes(metaFile.length());

    SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Date now = new Date();
    String strDate = sdfDate.format(now);
    metadataFile.setMetadataUpdateDate(strDate);

    researchObject.addFile(metadataFile);

    BatchIndexer<ResearchObject> indexer = new ROBatchIndexer(SeadQueryService.solr, null);
    indexer.add(researchObject);
    indexer.close();

    return "{\n" + "  \"response\" : \"Successfully added object - " + identifier + "\"" + "}";
}

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);/*www.  j  av a2  s  . c om*/
        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:cn.ctyun.amazonaws.auth.AbstractAWSSigner.java

protected byte[] hash(InputStream input) throws AmazonClientException {
    try {//from  w ww. j av a  2  s. c  om
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        DigestInputStream digestInputStream = new DigestInputStream(input, md);
        byte[] buffer = new byte[1024];
        while (digestInputStream.read(buffer) > -1)
            ;
        return digestInputStream.getMessageDigest().digest();
    } catch (Exception e) {
        throw new AmazonClientException("Unable to compute hash while signing request: " + e.getMessage(), e);
    }
}

From source file:pt.lunacloud.auth.AbstractAWSSigner.java

protected byte[] hash(InputStream input) throws LunacloudClientException {
    try {/* ww w  .  j  a v a 2s. com*/
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        DigestInputStream digestInputStream = new DigestInputStream(input, md);
        byte[] buffer = new byte[1024];
        while (digestInputStream.read(buffer) > -1)
            ;
        return digestInputStream.getMessageDigest().digest();
    } catch (Exception e) {
        throw new LunacloudClientException("Unable to compute hash while signing request: " + e.getMessage(),
                e);
    }
}

From source file:com.sina.auth.AbstractAWSSigner.java

protected byte[] hash(InputStream input) throws SCSClientException {
    try {/* w  w  w  .  j a  va  2s .  c om*/
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        DigestInputStream digestInputStream = new DigestInputStream(input, md);
        byte[] buffer = new byte[1024];
        while (digestInputStream.read(buffer) > -1)
            ;
        return digestInputStream.getMessageDigest().digest();
    } catch (Exception e) {
        throw new SCSClientException("Unable to compute hash while signing request: " + e.getMessage(), e);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.DatasetLoader.java

private void fetch(File aTarget, DataPackage... aPackages) throws IOException {
    // First validate if local copies are still up-to-date
    boolean reload = false;
    packageValidationLoop: for (DataPackage pack : aPackages) {
        File cachedFile = new File(aTarget, pack.getTarget());
        if (!cachedFile.exists()) {
            continue;
        }/*from  ww  w.  j  ava 2s . c  o  m*/

        if (pack.getSha1() != null) {
            String actual = getDigest(cachedFile, "SHA1");
            if (!pack.getSha1().equals(actual)) {
                LOG.info("Local SHA1 hash mismatch on [" + cachedFile + "] - expected [" + pack.getSha1()
                        + "] - actual [" + actual + "]");
                reload = true;
                break packageValidationLoop;
            } else {
                LOG.info("Local SHA1 hash verified on [" + cachedFile + "] - [" + actual + "]");
            }
        }

        if (pack.getMd5() != null) {
            String actual = getDigest(cachedFile, "MD5");
            if (!pack.getMd5().equals(actual)) {
                LOG.info("Local MD5 hash mismatch on [" + cachedFile + "] - expected [" + pack.getMd5()
                        + "] - actual [" + actual + "]");
                reload = true;
                break packageValidationLoop;
            } else {
                LOG.info("Local MD5 hash verified on [" + cachedFile + "] - [" + actual + "]");
            }
        }

    }

    // If any of the packages are outdated, clear the cache and download again
    if (reload) {
        LOG.info("Clearing local cache for [" + aTarget + "]");
        FileUtils.deleteQuietly(aTarget);
    }

    for (DataPackage pack : aPackages) {
        File cachedFile = new File(aTarget, pack.getTarget());

        if (cachedFile.exists()) {
            continue;
        }

        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IOException(e);
        }

        MessageDigest sha1;
        try {
            sha1 = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException e) {
            throw new IOException(e);
        }

        cachedFile.getParentFile().mkdirs();
        URL source = new URL(pack.getUrl());

        LOG.info("Fetching [" + cachedFile + "]");

        URLConnection connection = source.openConnection();
        connection.setRequestProperty("User-Agent", "Java");

        try (InputStream is = connection.getInputStream()) {
            DigestInputStream md5Filter = new DigestInputStream(is, md5);
            DigestInputStream sha1Filter = new DigestInputStream(md5Filter, sha1);
            FileUtils.copyInputStreamToFile(sha1Filter, cachedFile);

            if (pack.getMd5() != null) {
                String md5Hex = new String(Hex.encodeHex(md5Filter.getMessageDigest().digest()));
                if (!pack.getMd5().equals(md5Hex)) {
                    String message = "MD5 mismatch. Expected [" + pack.getMd5() + "] but got [" + md5Hex + "].";
                    LOG.error(message);
                    throw new IOException(message);
                }
            }

            if (pack.getSha1() != null) {
                String sha1Hex = new String(Hex.encodeHex(sha1Filter.getMessageDigest().digest()));
                if (!pack.getSha1().equals(sha1Hex)) {
                    String message = "SHA1 mismatch. Expected [" + pack.getSha1() + "] but got [" + sha1Hex
                            + "].";
                    LOG.error(message);
                    throw new IOException(message);
                }
            }
        }
    }

    // Perform a post-fetch action such as unpacking
    for (DataPackage pack : aPackages) {
        File cachedFile = new File(aTarget, pack.getTarget());
        File postActionCompleteMarker = new File(cachedFile.getPath() + ".postComplete");
        if (pack.getPostAction() != null && !postActionCompleteMarker.exists()) {
            try {
                pack.getPostAction().run(pack);
                FileUtils.touch(postActionCompleteMarker);
            } catch (IOException e) {
                throw e;
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
    }
}

From source file:com.quartz.AmazonQuartzJob.java

/**
 * Calculate content MD5 header values for feeds stored on disk.
 *///from   w w w . j  a v  a2s  . c om
public String computeContentMD5HeaderValue(FileInputStream fis) throws IOException, NoSuchAlgorithmException {
    DigestInputStream dis = new DigestInputStream(fis, MessageDigest.getInstance("MD5"));
    byte[] buffer = new byte[8192];
    while (dis.read(buffer) > 0)
        ;
    String md5Content = new String(
            org.apache.commons.codec.binary.Base64.encodeBase64(dis.getMessageDigest().digest()));
    // Effectively resets the stream to be beginning of the file
    // via a FileChannel.
    fis.getChannel().position(0);
    return md5Content;
}