Example usage for java.security DigestOutputStream DigestOutputStream

List of usage examples for java.security DigestOutputStream DigestOutputStream

Introduction

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

Prototype

public DigestOutputStream(OutputStream stream, MessageDigest digest) 

Source Link

Document

Creates a digest output stream, using the specified output stream and message digest.

Usage

From source file:org.apache.taverna.prov.Saver.java

private Path writeIfLocal(List<ExternalReferenceSPI> externalReferences, Path file, String mimeType)
        throws IOException {

    ValueCarryingExternalReference<?> valRef = null;
    for (ExternalReferenceSPI ref : externalReferences) {
        if (ref instanceof ValueCarryingExternalReference) {
            valRef = (ValueCarryingExternalReference<?>) ref;
            break;
        }//www  .ja  v  a 2s . c om
    }

    if (valRef == null) {
        return null;
    }

    String fileExtension;
    try {
        fileExtension = MimeTypes.getDefaultMimeTypes().forName(mimeType).getExtension();
    } catch (MimeTypeException e1) {
        fileExtension = "";
    }
    Path targetFile = file.resolveSibling(file.getFileName() + fileExtension);

    MessageDigest sha = null;
    MessageDigest sha512 = null;
    OutputStream output = Files.newOutputStream(targetFile);
    try {
        try {
            sha = MessageDigest.getInstance("SHA");
            output = new DigestOutputStream(output, sha);

            sha512 = MessageDigest.getInstance("SHA-512");
            output = new DigestOutputStream(output, sha512);
        } catch (NoSuchAlgorithmException e) {
            logger.info("Could not find digest", e);
        }

        IOUtils.copyLarge(valRef.openStream(getContext()), output);
    } finally {
        output.close();
    }

    if (sha != null) {
        getSha1sums().put(targetFile.toRealPath(), hexOfDigest(sha));
    }
    if (sha512 != null) {
        sha512.digest();
        getSha512sums().put(targetFile.toRealPath(), hexOfDigest(sha512));
    }

    return targetFile;
}

From source file:org.archive.wayback.util.FileDownloader.java

private void download(URL url, File target, boolean gz) throws IOException, NoSuchAlgorithmException {

    OutputStream os;/*from  w  ww.j a  v  a  2  s.  c  o m*/
    MessageDigest digester = null;
    InputStream is;
    if (gz) {
        is = new GZIPInputStream(url.openStream());
    } else {
        is = url.openStream();
    }

    FileOutputStream fos = new FileOutputStream(target);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    if (digest) {
        digester = MessageDigest.getInstance("MD5");
        os = new DigestOutputStream(bos, digester);
    } else {
        os = bos;
    }
    int BUF_SIZE = 4096;
    byte[] buffer = new byte[BUF_SIZE];
    for (int r = -1; (r = is.read(buffer, 0, BUF_SIZE)) != -1;) {
        os.write(buffer, 0, r);
    }
    is.close();
    os.flush();
    os.close();
    if (digest) {
        this.lastDigest = new String(Hex.encodeHex(digester.digest()));
    }
}

From source file:org.ardverk.dropwizard.assets.AssetsDirectory.java

/**
 * Loads an {@link Entry} from the underlying filesystem.
 *//* ww  w  . j  a v  a  2  s .  c  om*/
private Entry load(String requestURI) throws IOException {
    Path file = getFilePath(requestURI);

    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        try (DigestOutputStream dos = new DigestOutputStream(NopOutputStream.NULL, md)) {
            Files.copy(file, dos);
        }

        FileTime lastModified = Files.getLastModifiedTime(file);
        String etag = "\"" + Hex.encodeHexString(md.digest()) + "\"";
        Entry entry = new Entry(file, lastModified, etag);

        if (USE_CACHE) {
            synchronized (cache) {
                cache.put(requestURI, entry);
            }
        }

        return entry;
    } catch (NoSuchAlgorithmException err) {
        throw new IOException("NoSuchAlgorithmException", err);
    }
}

From source file:org.dataconservancy.dcs.lineage.http.support.RequestUtil.java

/**
 * Calculates a MD5 digest over the list of entity ids, suitable for use as an
 * ETag.  If the list is empty, {@code null} is returned.
 *
 * @param entityIds the entities//from   w w w. j av a  2  s .  c  om
 * @return the MD5 digest, or {@code null} if {@code entityIds} is empty.
 */
public static String calculateDigest(List<String> entityIds) {
    if (entityIds.isEmpty()) {
        return null;
    }

    NullOutputStream nullOut = new NullOutputStream();
    DigestOutputStream digestOut = null;

    try {
        digestOut = new DigestOutputStream(nullOut, MessageDigest.getInstance("MD5"));
        for (String id : entityIds) {
            IOUtils.write(id, digestOut);
        }
        digestOut.close();
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    return digestToHexString(digestOut.getMessageDigest().digest());
}

From source file:org.dataconservancy.dcs.util.http.ETagCalculator.java

public static String calculate(String id) {
    if (id.isEmpty()) {
        return null;
    }/* ww  w .  j a  v  a 2s.  co  m*/

    NullOutputStream nullOut = new NullOutputStream();
    DigestOutputStream digestOut = null;

    try {
        digestOut = new DigestOutputStream(nullOut, MessageDigest.getInstance("MD5"));
        IOUtils.write(id, digestOut);
        digestOut.close();
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    return digestToHexString(digestOut.getMessageDigest().digest());
}

From source file:org.exist.mongodb.xquery.gridfs.Store.java

void writeCompressed(GridFSInputFile gfsFile, StopWatch stopWatch, Item content, int dataType)
        throws NoSuchAlgorithmException, IOException, XPathException {
    // Store data compressed, add statistics
    try (OutputStream stream = gfsFile.getOutputStream()) {
        MessageDigest md = MessageDigest.getInstance("MD5");
        CountingOutputStream cosGZ = new CountingOutputStream(stream);
        GZIPOutputStream gos = new GZIPOutputStream(cosGZ);
        DigestOutputStream dos = new DigestOutputStream(gos, md);
        CountingOutputStream cosRaw = new CountingOutputStream(dos);

        stopWatch.start();/* w ww .j a  v  a2s.c  om*/
        ContentSerializer.serialize(content, context, cosRaw);
        cosRaw.flush();
        cosRaw.close();
        stopWatch.stop();

        long nrBytesRaw = cosRaw.getByteCount();
        long nrBytesGZ = cosGZ.getByteCount();
        String checksum = Hex.encodeHexString(dos.getMessageDigest().digest());

        BasicDBObject info = new BasicDBObject();
        info.put(Constants.EXIST_COMPRESSION, GZIP);
        info.put(Constants.EXIST_ORIGINAL_SIZE, nrBytesRaw);
        info.put(Constants.EXIST_ORIGINAL_MD5, checksum);
        info.put(Constants.EXIST_DATATYPE, dataType);
        info.put(Constants.EXIST_DATATYPE_TEXT, Type.getTypeName(dataType));

        gfsFile.setMetaData(info);

        LOG.info("original_md5:" + checksum);
        LOG.info("compression ratio:" + ((100l * nrBytesGZ) / nrBytesRaw));

    }
}

From source file:org.fejoa.library.crypto.KDFParameters.java

public HashValue hash(MessageDigest messageDigest) {
    OutputStream outputStream = new DigestOutputStream(new OutputStream() {
        @Override//from w ww.  j  ava2  s .c  om
        public void write(int i) throws IOException {

        }
    }, messageDigest);

    try {
        outputStream.write(kdfSettings.hash(messageDigest).getBytes());
        outputStream.write(kdfSalt);
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new HashValue(messageDigest.digest());
}

From source file:org.fejoa.library.crypto.UserKeyParameters.java

public HashValue hash(MessageDigest messageDigest) {
    OutputStream outputStream = new DigestOutputStream(new OutputStream() {
        @Override/* w  w  w.ja  va  2  s  . c om*/
        public void write(int i) throws IOException {

        }
    }, messageDigest);

    try {
        outputStream.write(kdfParameters.hash(messageDigest).getBytes());
        outputStream.write(userKeySalt);
        outputStream.write(hashAlgo.getBytes());
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new HashValue(messageDigest.digest());
}

From source file:org.geogit.storage.AbstractObjectDatabase.java

/**
 * @see org.geogit.storage.ObjectDatabase#put(org.geogit.storage.ObjectWriter)
 *///w ww  .jav  a2 s.  c o m
@Override
public final <T> ObjectId put(final ObjectWriter<T> writer) throws Exception {
    MessageDigest sha1;
    sha1 = MessageDigest.getInstance("SHA1");

    ByteArrayOutputStream rawOut = new ByteArrayOutputStream();

    DigestOutputStream keyGenOut = new DigestOutputStream(rawOut, sha1);
    // GZIPOutputStream cOut = new GZIPOutputStream(keyGenOut);
    LZFOutputStream cOut = new LZFOutputStream(keyGenOut);

    try {
        writer.write(cOut);
    } finally {
        // cOut.finish();
        cOut.flush();
        cOut.close();
        keyGenOut.flush();
        keyGenOut.close();
        rawOut.flush();
        rawOut.close();
    }

    final byte[] rawData = rawOut.toByteArray();
    final byte[] rawKey = keyGenOut.getMessageDigest().digest();
    final ObjectId id = new ObjectId(rawKey);
    putInternal(id, rawData, false);
    return id;
}

From source file:org.hibernate.search.elasticsearch.aws.impl.AWSPayloadHashingRequestInterceptor.java

private String computeContentHash(HttpRequest request) throws IOException {
    HttpEntity entity = getEntity(request);
    if (entity == null) {
        return DigestUtils.sha256Hex("");
    }/*w w  w  .j a v  a2 s  .  c  o m*/
    if (!entity.isRepeatable()) {
        throw new IllegalStateException("Cannot sign AWS requests with non-repeatable entities");
    }

    final MessageDigest digest = getSha256Digest();
    DigestOutputStream digestStream = new DigestOutputStream(DISCARDING_STREAM, digest);
    entity.writeTo(digestStream);
    return Hex.encodeHexString(digest.digest());
}