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:com.diversityarrays.dalclient.DalUtil.java

/**
 * Computes the MD5 checksum of the bytes in the InputStream.
 * The input is close()d on exit./*from   ww  w .j av a2  s.co m*/
 * @param input is the InputStream for which to compute the checksum
 * @return the MD5 checksum as a String of hexadecimal characters
 */
static public String computeMD5checksum(InputStream input) {
    DigestInputStream dis = null;
    Formatter formatter = null;
    try {
        MessageDigest md = MessageDigest.getInstance(DIGEST_MD5);
        dis = new DigestInputStream(input, md);
        while (-1 != dis.read())
            ;

        byte[] digest = md.digest();
        formatter = new Formatter();
        for (byte b : digest) {
            formatter.format("%02x", b); //$NON-NLS-1$
        }
        return formatter.toString();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException ignore) {
            }
        }
        if (formatter != null) {
            formatter.close();
        }
    }
}

From source file:ch.cyberduck.core.cf.CFPath.java

@Override
public void upload(final BandwidthThrottle throttle, final StreamListener listener,
        final TransferStatus status) {
    try {//from   w  w  w .  j  av  a 2  s .c o  m
        String md5sum = null;
        if (Preferences.instance().getBoolean("cf.upload.metadata.md5")) {
            this.getSession().message(MessageFormat
                    .format(Locale.localizedString("Compute MD5 hash of {0}", "Status"), this.getName()));
            md5sum = this.getLocal().attributes().getChecksum();
        }
        MessageDigest digest = null;
        if (!Preferences.instance().getBoolean("cf.upload.metadata.md5")) {
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                log.error("Failure loading MD5 digest", e);
            }
        }
        InputStream in = null;
        ResponseOutputStream<String> out = null;
        try {
            if (null == digest) {
                log.warn("MD5 calculation disabled");
                in = this.getLocal().getInputStream();
            } else {
                in = new DigestInputStream(this.getLocal().getInputStream(), digest);
            }
            out = this.write(status, md5sum);
            this.upload(out, in, throttle, listener, status);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
        if (null != digest && null != out) {
            this.getSession().message(MessageFormat
                    .format(Locale.localizedString("Compute MD5 hash of {0}", "Status"), this.getName()));
            // Obtain locally-calculated MD5 hash.
            String expectedETag = ServiceUtils.toHex(digest.digest());
            // Compare our locally-calculated hash with the ETag returned.
            final String result = out.getResponse();
            if (!expectedETag.equals(result)) {
                throw new IOException("Mismatch between MD5 hash of uploaded data (" + expectedETag
                        + ") and ETag returned (" + result + ") for object key: " + this.getKey());
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Object upload was automatically verified, the calculated MD5 hash "
                            + "value matched the ETag returned: " + this.getKey());
                }
            }
        }
    } catch (IOException e) {
        this.error("Upload failed", e);
    }
}

From source file:net.mindengine.galen.utils.GalenUtils.java

public static String calculateFileId(String fullPath) throws NoSuchAlgorithmException, FileNotFoundException {
    String fileName = new File(fullPath).getName();
    MessageDigest md = MessageDigest.getInstance("MD5");
    InputStream is = GalenUtils.findFileOrResourceAsStream(fullPath);
    new DigestInputStream(is, md);
    byte[] hashBytes = md.digest();

    return fileName + convertHashBytesToString(hashBytes);
}

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./*  w  w w . j a v a 2s  .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:org.hardisonbrewing.s3j.FileSyncer.java

public void put(String path, InputStream inputStream, long length) throws Exception {

    String url = getUrl(path);//ww  w. j  av a 2 s.  c  om

    HttpPut httpRequest = new HttpPut(url);
    httpRequest.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
    addHeaders(httpRequest, path);

    System.out.println("Uploading: " + url);
    HttpUtil.printHeaders(httpRequest);

    if (md5Digest == null) {
        md5Digest = MessageDigest.getInstance("MD5");
    } else {
        md5Digest.reset();
    }

    HttpResponse httpResponse;
    HttpEntity httpEntity = null;

    try {
        inputStream = new ProgressInputStream(inputStream, length);
        inputStream = new DigestInputStream(inputStream, md5Digest);
        httpRequest.setEntity(new InputStreamEntity(inputStream, length));
        httpResponse = httpClient.execute(httpRequest);
        httpEntity = httpResponse.getEntity();
    } finally {
        EntityUtils.consume(httpEntity);
    }

    System.out.println("  Response Headers");
    HttpUtil.printHeaders(httpResponse);

    HttpUtil.validateResponseCode(httpResponse);

    byte[] digest = md5Digest.digest();
    String digestHex = Hex.encodeHexString(digest);

    String etag = getHeaderValue(httpResponse, "ETag");

    if (!etag.equals(digestHex)) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("Uploaded digest (");
        stringBuffer.append(digestHex);
        stringBuffer.append(") does not match ETag (");
        stringBuffer.append(etag);
        stringBuffer.append(").");
        throw new IOException(stringBuffer.toString());
    }
}

From source file:com.galenframework.utils.GalenUtils.java

public static String calculateFileId(String fullPath) {
    try {// ww w . j a v a2  s.co m
        String fileName = new File(fullPath).getName();
        MessageDigest md = MessageDigest.getInstance("MD5");
        InputStream is = GalenUtils.findFileOrResourceAsStream(fullPath);
        new DigestInputStream(is, md);
        byte[] hashBytes = md.digest();
        return fileName + convertHashBytesToString(hashBytes);

    } catch (Exception ex) {
        throw new RuntimeException("Could not calculate file id", ex);
    }

}

From source file:de.huxhorn.sulky.blobs.impl.BlobRepositoryImpl.java

private boolean valid(String id, File file) {
    if (!validating) {
        return true;
    }/*from   w  w w .ja va 2s  . c  o m*/
    MessageDigest digest = createMessageDigest();

    FileInputStream input = null;
    try {
        input = new FileInputStream(file);
        DigestInputStream dis = new DigestInputStream(input, digest);
        for (;;) {
            if (dis.read() < 0) {
                break;
            }
        }
        byte[] hash = digest.digest();
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        return formatter.toString().equals(id);
    } catch (IOException e) {
        // ignore...
    } finally {
        IOUtils.closeQuietly(input);
    }
    return false;
}

From source file:hudson.Util.java

/**
 * Computes MD5 digest of the given input stream.
 *
 * @param source/*  w ww.  j ava 2s.c  om*/
 *      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:org.dspace.services.impl.storage.DSpaceStorageService.java

@Override
public Bitstream register(int assetstore, String path) throws StorageException {
    this.init();/*from  ww  w .ja  va  2 s  .  c o m*/

    // mark this bitstream as a registered bitstream
    String sInternalId = Bitstream.REGISTERED_FLAG + path;

    // Create a deleted bitstream row, using a separate DB connection
    Bitstream bitstream = new Bitstream();
    bitstream.setDeleted(true);
    bitstream.setInternalId(sInternalId);
    bitstream.setStoreNumber(assetstore);

    bitstreamDao.save(bitstream);

    // get a reference to the file
    GeneralFile file = getFile(bitstream);

    // read through a DigestInputStream that will work out the MD5
    //
    // DSpace refers to checksum, writes it in METS, and uses it as an
    // AIP filename (!), but never seems to validate with it. Furthermore,
    // DSpace appears to hardcode the algorithm to MD5 in some places--see
    // METSExport.java.
    //
    // To remain compatible with DSpace we calculate an MD5 checksum on
    // LOCAL registered files. But for REMOTE (e.g. SRB) files we
    // calculate an MD5 on just the fileNAME. The reasoning is that in the
    // case of a remote file, calculating an MD5 on the file itself will
    // generate network traffic to read the file's bytes. In this case it
    // would be better have a proxy process calculate MD5 and store it as
    // an SRB metadata attribute so it can be retrieved simply from SRB.
    //
    // TODO set this up as a proxy server process so no net activity

    // FIXME this is a first class HACK! for the reasons described above
    if (file instanceof LocalFile) {

        // get MD5 on the file for local file
        DigestInputStream dis = null;
        try {
            dis = new DigestInputStream(FileFactory.newFileInputStream(file), MessageDigest.getInstance("MD5"));
        } catch (NoSuchAlgorithmException e) {
            log.warn("Caught NoSuchAlgorithmException", e);
            throw new StorageException("Invalid checksum algorithm", e);
        } catch (IOException e) {
            log.error("File: " + file.getAbsolutePath() + " to be registered cannot be opened - is it "
                    + "really there?");
            throw new StorageException(e);
        }
        final int BUFFER_SIZE = 1024 * 4;
        final byte[] buffer = new byte[BUFFER_SIZE];
        try {
            while (true) {
                final int count = dis.read(buffer, 0, BUFFER_SIZE);
                if (count == -1) {
                    break;
                }
            }
            bitstream.setChecksum(Utils.toHex(dis.getMessageDigest().digest()));
            dis.close();
        } catch (IOException e) {
            throw new StorageException(e);
        }
    } else if (file instanceof SRBFile) {
        if (!file.exists()) {
            log.error("File: " + file.getAbsolutePath() + " is not in SRB MCAT");
            throw new StorageException("File is not in SRB MCAT");
        }

        // get MD5 on just the filename (!) for SRB file
        int iLastSlash = path.lastIndexOf('/');
        String sFilename = path.substring(iLastSlash + 1);
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            log.error("Caught NoSuchAlgorithmException", e);
            throw new StorageException("Invalid checksum algorithm", e);
        }
        bitstream.setChecksum(Utils.toHex(md.digest(sFilename.getBytes())));
    } else {
        throw new StorageException("Unrecognized file type - " + "not local, not SRB");
    }

    bitstream.setChecksumAlgorithm("MD5");
    bitstream.setSize(file.length());
    bitstream.setDeleted(false);

    bitstreamDao.save(bitstream);

    if (log.isDebugEnabled()) {
        log.debug("Stored bitstream " + bitstream.getID() + " in file " + file.getAbsolutePath());
    }
    return bitstream;
}

From source file:de.huxhorn.sulky.blobs.impl.BlobRepositoryImpl.java

private String copyAndHash(InputStream input, File into) throws IOException {
    MessageDigest digest = createMessageDigest();

    DigestInputStream dis = new DigestInputStream(input, digest);
    IOException ex;/*from www .  j av  a 2s  . c om*/
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(into);
        IOUtils.copyLarge(dis, fos);
        byte[] hash = digest.digest();
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    } catch (IOException e) {
        ex = e;
    } finally {
        IOUtils.closeQuietly(dis);
        IOUtils.closeQuietly(fos);
    }
    if (logger.isWarnEnabled())
        logger.warn("Couldn't retrieve data from input!", ex);
    deleteTempFile(into);
    throw ex;
}