Java Checksum Calculate calculateChecksums(Optional zos, InputStream inputStream, Set checksumAlgorithms)

Here you can find the source of calculateChecksums(Optional zos, InputStream inputStream, Set checksumAlgorithms)

Description

calculate Checksums

License

LGPL

Declaration

public static Map<String, String> calculateChecksums(Optional<ZipOutputStream> zos, InputStream inputStream,
            Set<String> checksumAlgorithms) throws NoSuchAlgorithmException, IOException 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.io.IOException;
import java.io.InputStream;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;

import java.util.zip.ZipOutputStream;
import javax.xml.bind.DatatypeConverter;

public class Main {
    public static Map<String, String> calculateChecksums(Optional<ZipOutputStream> zos, InputStream inputStream,
            Set<String> checksumAlgorithms) throws NoSuchAlgorithmException, IOException {
        byte[] buffer = new byte[4096];
        Map<String, String> values = new HashMap<>();

        // instantiate different checksum algorithms
        Map<String, MessageDigest> algorithms = new HashMap<>();
        for (String alg : checksumAlgorithms) {
            algorithms.put(alg, MessageDigest.getInstance(alg));
        }//from w  w w  .  j av  a2  s.  com

        // calculate value for each one of the algorithms
        int numRead;
        do {
            numRead = inputStream.read(buffer);
            if (numRead > 0) {
                for (Entry<String, MessageDigest> alg : algorithms.entrySet()) {
                    alg.getValue().update(buffer, 0, numRead);
                }

                if (zos.isPresent()) {
                    zos.get().write(buffer, 0, numRead);
                }
            }
        } while (numRead != -1);

        // generate hex versions of the digests
        algorithms.forEach((alg, dig) -> values.put(alg, DatatypeConverter.printHexBinary(dig.digest())));

        return values;
    }
}

Related

  1. calcChecksum(byte[] buffer, int start, int end)
  2. calcCheckSum(byte[] bytes, int num)
  3. calcCheckSum(byte[] data, int offset, int maxIdx)
  4. calcChecksum(String value, int length)
  5. calculateChecksum(InputStream is, String algorithm)
  6. checkSum(boolean[] a)
  7. checkSum(byte abyte0[])
  8. checksum(byte current, final byte[] data, final int offset, final int length)
  9. checkSum(byte value)