Example usage for java.security DigestInputStream read

List of usage examples for java.security DigestInputStream read

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

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

public static String computeHash(URL url) {

    InputStream from = null;/* w  w w .  j  ava  2  s . c o  m*/
    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:com.quartz.AmazonQuartzJob.java

/**
 * Calculate content MD5 header values for feeds stored on disk.
 *//*w w w .j a  v a  2  s. c o m*/
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;
}

From source file:cn.ctyun.amazonaws.auth.AbstractAWSSigner.java

protected byte[] hash(InputStream input) throws AmazonClientException {
    try {/*from   w w  w  .  ja  v 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 {/*from www .  jav a  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 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 {/*from w  ww .j  a  v  a  2 s .  c o  m*/
        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:com.mum.app.AutoSubmitPriceApp.java

private String computeContentMD5HeaderValue(InputStream fis) throws IOException, NoSuchAlgorithmException {

    DigestInputStream dis = new DigestInputStream(fis, MessageDigest.getInstance("MD5"));

    byte[] buffer = new byte[8192];
    while (dis.read(buffer) > 0)
        ;//  w w  w .  ja  v  a  2s. com

    String md5Content = new String(
            org.apache.commons.codec.binary.Base64.encodeBase64(dis.getMessageDigest().digest()));
    return md5Content;
}

From source file:org.deventropy.shared.utils.DirectoryArchiverUtilTest.java

private byte[] getMd5Digest(final InputStream inputStream, final boolean closeStream) throws IOException {
    try {//from   w w  w.ja  v a  2  s  .  c  om
        final MessageDigest md = MessageDigest.getInstance("MD5");
        final DigestInputStream dis = new DigestInputStream(inputStream, md);

        final byte[] buf = new byte[MAX_FILE_SIZE];
        int len = 0;
        while (len != -1) {
            len = dis.read(buf);
        }
        return md.digest();
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    } finally {
        if (closeStream && null != inputStream) {
            inputStream.close();
        }
    }
}

From source file:com.jrummyapps.android.safetynet.SafetyNetHelper.java

@Nullable
private String getApkDigestSha256() {
    try {//from   w w  w  . j  a  v a 2  s .  com
        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:at.diamonddogs.net.WebClient.java

private void saveData(InputStream i) throws IOException {
    if (i == null) {
        return;//from   ww w.  ja  v  a 2 s .c o m
    }
    TempFile tmp = webRequest.getTmpFile().second;
    FileOutputStream fos = null;
    try {

        MessageDigest md = MessageDigest.getInstance("MD5");
        DigestInputStream dis = new DigestInputStream(i, md);

        File file = new File(tmp.getPath());
        Log.d(TAG, file.getAbsolutePath() + "can write: " + file.canWrite());
        if (file.exists() && !tmp.isAppend()) {
            file.delete();
        }
        byte buffer[] = new byte[READ_BUFFER_SIZE];
        fos = new FileOutputStream(file, tmp.isAppend());
        int bytesRead = 0;
        while ((bytesRead = dis.read(buffer)) != -1) {
            if (!webRequest.isCancelled()) {
                fos.write(buffer, 0, bytesRead);
                publishDownloadProgress(bytesRead);
            } else {
                Log.i(TAG, "Cancelled Download");
                break;
            }
        }
        fos.flush();
        fos.close();

        if (webRequest.isCancelled()) {
            Log.i(TAG, "delete file due to canclled download: " + file.getName());
            file.delete();
        } else {

            if (tmp.isUseChecksum()) {
                String md5 = new String(Hex.encodeHex(md.digest()));

                Log.d(TAG, "md5 check, original: " + tmp.getChecksum() + " file: " + md5);

                if (!md5.equalsIgnoreCase(tmp.getChecksum())) {
                    throw new IOException("Error while downloading File.\nOriginal Checksum: "
                            + tmp.getChecksum() + "\nChecksum: " + md5);
                }
            }
        }

    } catch (Exception e) {
        if (fos != null && tmp.isAppend()) {
            fos.flush();
            fos.close();
        }
        Log.e(TAG, "Failed download", e);
        // Please do not do that - that hides the original error!
        throw new IOException(e.getMessage());

        // Who ever changed this... new IOException(e) is API level 9!!! and
        // gives a nice NoSuchMethodException :)
        // throw new IOException(e);
    }
}

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.//from  w  ww  .j ava 2 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);
    }
}