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.springframework.integration.aws.core.AWSCommonUtils.java

/**
 * Generates the MD5 hash of the file provided
 * @param file/*w  w w  . j  a  v a  2 s. c om*/
 */
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:org.slc.sli.test.utils.DataUtils.java

public static final String createMd5ForFile(String file) {
    File myFile = new File(file);
    DigestInputStream dis = null;
    try {/*from w w  w .ja  va 2  s .  c o  m*/
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.reset();
        dis = new DigestInputStream(new FileInputStream(myFile), md);
        byte[] buf = new byte[1024];
        while (dis.read(buf, 0, 1024) != -1) {
        }
        return Hex.encodeHexString(dis.getMessageDigest().digest());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.carlspring.strongbox.storage.metadata.nuget.TempNupkgFile.java

/**
 * Creates a temporary file based on the stream.
 *
 * @param inputStream/*  ww  w.j ava 2  s . c  o  m*/
 *            data stream
 * @param targetFile
 *            file to copy the package to
 * @return data file
 * @throws IOException
 *             read / write error
 * @throws NoSuchAlgorithmException
 *             the system does not have an algorithm for calculating the
 *             value of HASH
 */
private static String copyDataAndCalculateHash(InputStream inputStream, File targetFile)
        throws IOException, NoSuchAlgorithmException {
    MessageDigest messageDigest = MessageDigest.getInstance(MessageDigestAlgorithms.SHA_512);
    DigestInputStream digestInputStream = new DigestInputStream(inputStream, messageDigest);

    try (FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
            ReadableByteChannel src = Channels.newChannel(digestInputStream);
            FileChannel dest = fileOutputStream.getChannel();) {
        fastChannelCopy(src, dest);

        byte[] digest = digestInputStream.getMessageDigest().digest();

        return DatatypeConverter.printBase64Binary(digest);
    }
}

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

public static CloseableHttpResponse sendChunk(DigestInputStream dis, int size, String method, URI uri,
        String filename, String mimeType, CloseableHttpClient http, boolean inProgress) throws Exception {
    // System.out.println(String.format("Sending chunk to %s, filename = %s, chunk size = %d, MIME-Type = %s, In-Progress = %s ... ", uri.toString(),
    // filename, size, mimeType, Boolean.toString(inProgress)));
    byte[] chunk = readChunk(dis, size);
    String md5 = new String(Hex.encodeHex(dis.getMessageDigest().digest()));
    HttpUriRequest request = RequestBuilder.create(method).setUri(uri).setConfig(RequestConfig.custom()
            /*/*  www  .j  a v  a2  s. c  o  m*/
             * When using an HTTPS-connection EXPECT-CONTINUE must be enabled, otherwise buffer overflow may follow
             */
            .setExpectContinueEnabled(true).build()) //
            .addHeader("Content-Disposition", String.format("attachment; filename=%s", filename)) //
            .addHeader("Content-MD5", md5) //
            .addHeader("Packaging", BAGIT_URI) //
            .addHeader("In-Progress", Boolean.toString(inProgress)) //
            .setEntity(new ByteArrayEntity(chunk, ContentType.create(mimeType))) //
            .build();
    CloseableHttpResponse response = http.execute(request);
    // System.out.println("Response received.");
    return response;
}

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

protected String retrieveMD5(DigestInputStream md5Stream) {
    final byte[] digInBytes = md5Stream.getMessageDigest().digest();
    return String.valueOf(Hex.encodeHex(digInBytes));
}

From source file:org.opensingular.form.wicket.mapper.attachment.upload.FileUploadManager.java

public FileUploadInfo createFile(UploadInfo uploadInfo, String fileName, InputStream input) throws IOException {

    getLogger().debug("createFile({},{},{})", uploadInfo.getUploadId(), fileName, input);

    final Path path;
    final IAttachmentPersistenceHandler handler;
    final IAttachmentRef attachment;
    final FileUploadInfo info;
    final File file;

    handler = uploadInfo.getPersistenceHandlerSupplier().get();
    path = uploadPathHandler.getLocalFilePath(attachmentKeyFactory.make().toString());
    file = path.toFile();//  w  w w . ja v a 2  s. c om

    file.deleteOnExit();

    DigestInputStream din = HashUtil.toSHA1InputStream(input);
    Files.copy(din, path);

    attachment = handler.addAttachment(file, Files.size(path), fileName,
            HashUtil.bytesToBase16(din.getMessageDigest().digest()));
    info = new FileUploadInfo(attachment);

    fileUploadInfoRepository.add(info);

    return info;
}

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

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

From source file:org.duracloud.chunk.ChunkableContentTest.java

private void verifyTotalChunkChecksum() throws Exception {
    MessageDigest md5 = MessageDigest.getInstance(Algorithm.MD5.name());
    DigestInputStream istream;
    for (File chunk : chunkFiles) {
        istream = new DigestInputStream(new FileInputStream(chunk), md5);
        read(istream);//from  w  w  w  .  ja  v a 2s .  c  o m
        md5 = istream.getMessageDigest();
        IOUtils.closeQuietly(istream);
    }

    Assert.assertNotNull(md5);
    Assert.assertTrue(MessageDigest.isEqual(contentChecksum.digest(), md5.digest()));

}

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.
 *///from   w ww. j av a 2 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:org.eclipse.hawkbit.artifact.repository.ArtifactStoreTest.java

@Test
@Description("Ensures that search by MD5 hash finds the expected results.")
public void findArtifactByMD5Hash() throws NoSuchAlgorithmException {
    final int filelengthBytes = 128;
    final String filename = "testfile.json";
    final String contentType = "application/json";

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