Example usage for java.security DigestInputStream close

List of usage examples for java.security DigestInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:com.aurel.track.dbase.HandleHome.java

public static String computeHash(URL url) {

    InputStream from = null;//from   w  w w.  j av a  2s .  c om
    String hash = "";

    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        from = url.openStream(); // Create input stream
        byte[] buffer = new byte[4096]; // To hold file contents
        DigestInputStream dis = new DigestInputStream(from, md);
        while (dis.read(buffer) != -1) {

        }

        byte[] digest = md.digest();

        dis.close();
        from.close();

        hash = DatatypeConverter.printHexBinary(digest);

    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }
    // Always close the stream, even if exceptions were thrown
    finally {
        if (from != null)
            try {
                from.close();
            } catch (IOException e) {
            }
    }
    return hash;
}

From source file:org.apache.jackrabbit.oak.spi.blob.FileBlobStore.java

@Override
public String writeBlob(String tempFilePath) throws IOException {
    File file = new File(tempFilePath);
    InputStream in = new FileInputStream(file);
    MessageDigest messageDigest;/* w w  w. jav  a2  s . com*/
    try {
        messageDigest = MessageDigest.getInstance(HASH_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }
    DigestInputStream din = new DigestInputStream(in, messageDigest);
    long length = file.length();
    try {
        while (true) {
            int len = din.read(buffer, 0, buffer.length);
            if (len < 0) {
                break;
            }
        }
    } finally {
        din.close();
    }
    ByteArrayOutputStream idStream = new ByteArrayOutputStream();
    idStream.write(TYPE_HASH);
    IOUtils.writeVarInt(idStream, 0);
    IOUtils.writeVarLong(idStream, length);
    byte[] digest = messageDigest.digest();
    File f = getFile(digest, false);
    if (f.exists()) {
        file.delete();
    } else {
        File parent = f.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        file.renameTo(f);
    }
    IOUtils.writeVarInt(idStream, digest.length);
    idStream.write(digest);
    byte[] id = idStream.toByteArray();
    String blobId = StringUtils.convertBytesToHex(id);
    usesBlobId(blobId);
    return blobId;
}

From source file:com.github.nlloyd.hornofmongo.MongoScope.java

public static Object md5sumFile(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
    assertSingleArgument(args);/*  ww  w .  j  a  v  a2  s  .  com*/
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        Context.throwAsScriptRuntimeEx(e);
    }
    File inFile;
    try {
        inFile = resolveFilePath((MongoScope) thisObj, Context.toString(args[0])).getCanonicalFile();
    } catch (IOException e) {
        Context.throwAsScriptRuntimeEx(e);
        return null;
    }
    InputStream in = null;
    DigestInputStream dis = null;
    try {
        in = new BufferedInputStream(new FileInputStream(inFile));
        dis = new DigestInputStream(in, md);
        while (dis.available() > 0)
            dis.read();
        byte[] digest = md.digest();
        String hexStr = Hex.encodeHexString(digest);
        return hexStr;
    } catch (FileNotFoundException e) {
        Context.throwAsScriptRuntimeEx(e);
    } catch (IOException e) {
        Context.throwAsScriptRuntimeEx(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e) {
            }
        }
    }
    return Undefined.instance;
}

From source file:com.qut.middleware.metadata.source.impl.MetadataSourceBase.java

/**
 * Reads the provided input stream, calculates and updates an internal hash.
 * If the internal hash has changed, the byte array obtained from reading the
 * InputStream is passed to the processMetadata method, along with the
 * provided MetadataProcessor object./*  w ww .  j a v  a2 s . c  o m*/
 * @param input Input stream to send 
 * @param processor
 * @throws IOException
 */
protected void readMetadata(InputStream input, MetadataProcessor processor) throws IOException {
    byte[] buf = new byte[BUFFER_LENGTH];
    long startTime = System.currentTimeMillis();

    // Pipe everything through a digest stream so we get a hash value at the end
    DigestInputStream digestInput = new DigestInputStream(input, this.getMessageDigestInstance());
    BufferedInputStream bufferedInput = new BufferedInputStream(digestInput);

    ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();

    this.logger.debug("Metadata source {} - going to read input stream", this.getLocation());
    int bytes = 0;
    while ((bytes = bufferedInput.read(buf)) != -1) {
        byteOutput.write(buf, 0, bytes);
    }

    bufferedInput.close();
    digestInput.close();
    byteOutput.close();

    long endTime = System.currentTimeMillis();

    byte[] document = byteOutput.toByteArray();
    byte[] hash = digestInput.getMessageDigest().digest();

    this.logger.debug("Metadata source {} - read {} bytes of metadata in {} ms",
            new Object[] { this.getLocation(), document.length, (endTime - startTime) });

    // If the document has changed, the hash will be updated, and then we go to process the new document
    if (this.updateDigest(hash)) {
        startTime = System.currentTimeMillis();
        this.logger.debug("Metadata source {} - updated. Going to process.", this.getLocation());
        this.processMetadata(document, processor);
        endTime = System.currentTimeMillis();
        this.logger.info("Metadata source {} - processed document and updated cache in {} ms",
                this.getLocation(), (endTime - startTime));
    } else {
        this.logger.info("Metadata source {} - has not been updated.", this.getLocation());
    }
}

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./*  ww w .ja  v  a  2  s  .c  o 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:com.jrummyapps.android.safetynet.SafetyNetHelper.java

@Nullable
private String getApkDigestSha256() {
    try {/*from www. j  av a  2s .co  m*/
        FileInputStream fis = new FileInputStream(context.getPackageCodePath());
        MessageDigest md = MessageDigest.getInstance(SHA_256);
        try {
            DigestInputStream dis = new DigestInputStream(fis, md);
            byte[] buffer = new byte[2048];
            while (dis.read(buffer) != -1) {
                //
            }
            dis.close();
        } finally {
            fis.close();
        }
        return Base64.encodeToString(md.digest(), Base64.NO_WRAP);
    } catch (IOException | NoSuchAlgorithmException e) {
        return null;
    }
}

From source file:org.dspace.pack.bagit.Bag.java

public void addData(String relPath, long size, InputStream is) throws IOException {
    if (filled) {
        throw new IllegalStateException("Cannot add data to filled bag");
    }/*from   w w  w .jav a  2s.c om*/
    // wrap stream in digest stream
    DigestInputStream dis = null;
    try {
        dis = new DigestInputStream(is, MessageDigest.getInstance(CS_ALGO));
        FileOutputStream fos = new FileOutputStream(dataFile(relPath));
        // attempt to optimize copy in various ways - TODO
        Utils.copy(dis, fos);
        fos.close();
        dis.close();
        is.close();
    } catch (NoSuchAlgorithmException nsaE) {
        throw new IOException("no algorithm: " + CS_ALGO);
    }
    // record checksum
    String brPath = "data/" + relPath;
    manWriter.writeProperty(Utils.toHex(dis.getMessageDigest().digest()), brPath);
}

From source file:stargate.drivers.recipe.sha1fixed.SHA1FixedChunkRecipeGeneratorDriver.java

@Override
public synchronized Recipe getRecipe(DataObjectMetadata metadata, InputStream is) throws IOException {
    if (metadata == null || metadata.isEmpty()) {
        throw new IllegalArgumentException("metadata is null or empty");
    }//ww  w  .  j  a v a 2 s. c o m

    if (is == null) {
        throw new IllegalArgumentException("is is null");
    }

    List<RecipeChunk> chunk = new ArrayList<RecipeChunk>();

    int bufferSize = Math.min(this.chunkSize, BUFFER_SIZE);
    byte[] buffer = new byte[bufferSize];

    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        DigestInputStream dis = new DigestInputStream(is, messageDigest);

        long chunkOffset = 0;

        while (chunkOffset < metadata.getObjectSize()) {
            int chunkLength = 0;
            int nread = 0;
            int toread = this.chunkSize;

            while ((nread = dis.read(buffer, 0, Math.min(toread, bufferSize))) > 0) {
                chunkLength += nread;
                toread -= nread;
                if (toread == 0) {
                    break;
                }
            }

            byte[] digest = messageDigest.digest();
            chunk.add(new RecipeChunk(chunkOffset, chunkLength, digest));
            messageDigest.reset();

            if (nread <= 0) {
                //EOF
                break;
            }

            chunkOffset += chunkLength;
        }

        dis.close();
    } catch (NoSuchAlgorithmException ex) {
        throw new IOException(ex);
    }

    return new Recipe(metadata, HASH_ALGORITHM, this.chunkSize, chunk);
}

From source file:de.burlov.amazon.s3.dirsync.DirSync.java

private byte[] digestFile(File file, MessageDigest digest) throws IOException {
    DigestInputStream in = new DigestInputStream(new FileInputStream(file), digest);
    IOUtils.copy(in, new NullOutputStream());
    in.close();
    return in.getMessageDigest().digest();
}

From source file:com.example.download.DownloadThread.java

/**
 * Prepare the destination file to receive data.  If the file already exists, we'll set up
 * appropriately for resumption.// ww w.  j  av  a2 s .c  o m
 */
private void setupDestinationFile(State state, InnerState innerState) throws StopRequest {

    if (!TextUtils.isEmpty(state.mFilename)) {
        // only true if we've already run a thread for this download
        if (!Helper.isFilenameValid(state.mFilename, state.mSourceType)) {
            // this should never happen
            throw new StopRequest(DownloadManager.Impl.STATUS_FILE_ERROR,
                    "found invalid internal destination filename");
        }

        // We're resuming a download that got interrupted
        File f = new File(state.mFilename);
        if (f.exists()) {
            long fileLength = f.length();
            if (fileLength == 0) {
                // The download hadn't actually started, we can restart from scratch
                f.delete();
                state.mFilename = null;
            } else if (mInfo.mETag == null) {
                // This should've been caught upon failure
                f.delete();
                throw new StopRequest(DownloadManager.Impl.STATUS_CANNOT_RESUME,
                        "Trying to resume a download that can't be resumed");
            } else {
                // All right, we'll be able to resume this download
                try {
                    state.mStream = new FileOutputStream(state.mFilename, true);
                    FileInputStream fis = new FileInputStream(state.mFilename);
                    DigestInputStream dis = new DigestInputStream(fis, state.mDigester);
                    byte[] buffer = new byte[8192];
                    while (dis.read(buffer) != -1) {
                        // read the digest
                    }
                    dis.close();
                    fis.close();
                } catch (FileNotFoundException exc) {
                    throw new StopRequest(DownloadManager.Impl.STATUS_FILE_ERROR,
                            "while opening destination for resuming: " + exc.toString(), exc);
                } catch (IOException e) {
                    throw new StopRequest(DownloadManager.Impl.STATUS_FILE_ERROR,
                            "while opening destination for resuming: " + e.toString(), e);
                }
                innerState.mBytesSoFar = (int) fileLength;
                if (mInfo.mTotalBytes != -1) {
                    innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
                }
                innerState.mHeaderETag = mInfo.mETag;
                innerState.mContinuingDownload = true;
            }
        }
    }

    if (state.mStream != null && mInfo.mDestination == DownloadManager.Impl.DESTINATION_EXTERNAL) {
        closeDestination(state);
    }
}