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.zimbra.cs.store.triton.TritonBlobStoreManager.java

@Override
public byte[] getHash(Blob blob) throws ServiceException, IOException {
    MessageDigest digest = newDigest();
    DigestInputStream dis = null;
    InputStream bis = null;/*from w  ww .j av  a  2  s .c o m*/
    try {
        bis = blob.getInputStream();
        dis = new DigestInputStream(bis, digest);
        while (dis.read() >= 0) {
        }
        return digest.digest();
    } finally {
        ByteUtil.closeStream(bis);
        ByteUtil.closeStream(dis);
    }
}

From source file:org.opf_labs.fmts.fidget.TikaIdentifier.java

static final String hash64K(final InputStream stream) throws IOException {
    SHA256.reset();/*  ww  w.j a va 2s  .  c  o  m*/
    // Create input streams for digest calculation
    DigestInputStream SHA256Stream = new DigestInputStream(stream, SHA256);
    byte[] buff = new byte[HASH_LENGTH];
    // Read up to the 64K in on read
    SHA256Stream.read(buff, 0, HASH_LENGTH);
    // Return the new instance from the calulated details
    return Hex.encodeHexString(SHA256.digest());
}

From source file:hudson.plugins.ec2.EC2AxisPrivateKey.java

static String digest(PrivateKey k) throws IOException {
    try {//from   www . j  av  a2  s.  co  m
        MessageDigest md5 = MessageDigest.getInstance("SHA1");

        DigestInputStream in = new DigestInputStream(new ByteArrayInputStream(k.getEncoded()), md5);
        try {
            while (in.read(new byte[128]) > 0)
                ; // simply discard the input
        } finally {
            in.close();
        }
        StringBuilder buf = new StringBuilder();
        char[] hex = Hex.encodeHex(md5.digest());
        for (int i = 0; i < hex.length; i += 2) {
            if (buf.length() > 0)
                buf.append(':');
            buf.append(hex, i, 2);
        }
        return buf.toString();
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    }
}

From source file:at.diamonddogs.net.WebClient.java

private void saveData(InputStream i) throws IOException {
    if (i == null) {
        return;//from w  ww  .ja  va  2  s .co 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:de.csdev.ebus.cfg.std.EBusConfigurationReader.java

@Override
public IEBusCommandCollection loadConfigurationCollection(URL url)
        throws IOException, EBusConfigurationReaderException {

    if (registry == null) {
        throw new RuntimeException("Unable to load configuration without EBusType set!");
    }/*from   w  w w .ja  v  a  2  s . c  om*/

    if (url == null) {
        throw new IllegalArgumentException("Required argument url is null!");
    }

    Type merchantListType = new TypeToken<List<EBusValueDTO>>() {
    }.getType();

    Gson gson = new Gson();
    gson = new GsonBuilder().registerTypeAdapter(merchantListType, new EBusValueJsonDeserializer()).create();

    MessageDigest md = null;

    try {
        md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }

    // collect md5 hash while reading file
    DigestInputStream dis = new DigestInputStream(url.openStream(), md);

    EBusCollectionDTO collection = gson.fromJson(new InputStreamReader(dis), EBusCollectionDTO.class);

    EBusCommandCollection commandCollection = new EBusCommandCollection(collection.getId(),
            collection.getLabel(), collection.getDescription(), collection.getProperties());

    // add md5 hash
    commandCollection.setSourceHash(md.digest());
    commandCollection.setIdentification(collection.getIdentification());

    // parse the template block
    parseTemplateConfiguration(collection);

    if (collection.getCommands() != null) {
        for (EBusCommandDTO commandDto : collection.getCommands()) {
            if (commandDto != null) {
                commandCollection.addCommand(parseTelegramConfiguration(commandCollection, commandDto));
            }
        }
    }

    return commandCollection;
}

From source file:org.eclipse.packagedrone.utils.rpm.build.PayloadRecorder.java

public Result addFile(final String targetPath, final Path path, final Consumer<CpioArchiveEntry> customizer)
        throws IOException {
    final long size = Files.size(path);

    final CpioArchiveEntry entry = new CpioArchiveEntry(targetPath);
    entry.setSize(size);/*w ww.j av a 2s.c  o  m*/

    if (customizer != null) {
        customizer.accept(entry);
    }

    this.archiveStream.putArchiveEntry(entry);

    MessageDigest digest;
    try {
        digest = createDigest();
    } catch (final NoSuchAlgorithmException e) {
        throw new IOException(e);
    }

    try (InputStream in = new BufferedInputStream(Files.newInputStream(path))) {
        ByteStreams.copy(new DigestInputStream(in, digest), this.archiveStream);
    }

    this.archiveStream.closeArchiveEntry();

    return new Result(size, digest.digest());
}

From source file:org.cdmckay.coffeep.Program.java

private static ClassFile getClassFile(JavaFileObject fileObject, CoffeepSystemInfo systemInfo)
        throws IOException, ConstantPoolException {
    if (fileObject == null) {
        throw new IllegalArgumentException("fileObject cannot be null");
    }//from   w w  w .  j a  v a  2 s .  c  o  m
    if (systemInfo == null) {
        throw new IllegalArgumentException("systemInfo cannot be null");
    }

    InputStream inputStream = fileObject.openInputStream();
    try {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.warn("Exception while getting MD5 MessageDigest", e);
        }

        DigestInputStream digestInputStream = new DigestInputStream(inputStream, messageDigest);
        CountingInputStream countingInputStream = new CountingInputStream(digestInputStream);

        Attribute.Factory attributeFactory = new Attribute.Factory();
        ClassFile classFile = ClassFile.read(countingInputStream, attributeFactory);

        systemInfo.classFileUri = fileObject.toUri();
        systemInfo.classFileSize = countingInputStream.getSize();
        systemInfo.lastModifiedTimestamp = fileObject.getLastModified();
        if (messageDigest != null) {
            systemInfo.digestAlgorithm = messageDigest.getAlgorithm();
            systemInfo.digest = new BigInteger(1, messageDigest.digest()).toString(16);
        }

        return classFile;
    } finally {
        inputStream.close();
    }
}

From source file:com.vmware.identity.idm.CommonUtil.java

public static String Computesha256Hash(File secretFile) throws IOException, NoSuchAlgorithmException {
    FileInputStream fs = null;//from   w w  w. java2s. co  m
    try {
        fs = new FileInputStream(secretFile);
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        DigestInputStream dis = new DigestInputStream(fs, md);
        while ((dis.read()) != -1)
            ;
        BigInteger bi = new BigInteger(md.digest());
        return bi.toString(64);
    } finally {
        if (fs != null) {
            fs.close();
        }
    }
}

From source file:uk.bl.wa.util.HashedCachedInputStream.java

/**
 * @param header/*w  w  w .j  ava  2  s.co  m*/
 * @param in
 * @param length
 */
private void init(ArchiveRecordHeader header, InputStream in, long length) {
    url = Normalisation.sanitiseWARCHeaderValue(header.getUrl());
    try {
        digest = MessageDigest.getInstance(MessageDigestAlgorithms.SHA_1);
    } catch (NoSuchAlgorithmException e) {
        log.error("Hashing: " + url + "@" + header.getOffset(), e);
    }

    try {
        if (header.getHeaderFieldKeys().contains(HEADER_KEY_PAYLOAD_DIGEST)) {
            headerHash = (String) header.getHeaderValue(HEADER_KEY_PAYLOAD_DIGEST);
        }

        // Create a suitable outputstream for caching the content:
        OutputStream cache = null;
        if (length < inMemoryThreshold) {
            inMemory = true;
            cache = new ByteArrayOutputStream();
        } else {
            inMemory = false;
            cacheFile = File.createTempFile("warc-indexer", ".cache");
            cacheFile.deleteOnExit();
            cache = new FileOutputStream(cacheFile);
        }

        DigestInputStream dinput = new DigestInputStream(in, digest);

        long toCopy = length;
        if (length > this.onDiskThreshold) {
            toCopy = this.onDiskThreshold;
        }
        IOUtils.copyLarge(dinput, cache, 0, toCopy);
        cache.close();

        // Read the remainder of the stream, to get the hash.
        if (length > this.onDiskThreshold) {
            truncated = true;
            IOUtils.skip(dinput, length - this.onDiskThreshold);
        }

        hash = "sha1:" + Base32.encode(digest.digest());

        // For response records, check the hash is consistent with any header hash:
        if ((headerHash != null) && (hash.length() == headerHash.length())) {
            if (header.getHeaderFieldKeys().contains(HEADER_KEY_TYPE) && header.getHeaderValue(HEADER_KEY_TYPE)
                    .equals(WARCConstants.WARCRecordType.response.toString())) {
                if (!headerHash.equals(hash)) {
                    log.error("Hashes are not equal for this input!");
                    log.error(" - payload hash from header = " + headerHash);
                    log.error(" - payload hash from content = " + hash);
                    throw new RuntimeException("Hash check failed!");
                } else {
                    log.debug("Hashes were found to match for " + url);
                }
            } else {
                // For revisit records, use the hash of the revisited payload:
                // TODO this should actually only do it for revisit type records.
                this.hash = this.headerHash;
            }
        }

        // Now set up the inputStream
        if (inMemory) {
            this.cacheBytes = ((ByteArrayOutputStream) cache).toByteArray();
            // Encourage GC
            cache = null;
        }
    } catch (Exception i) {
        log.error("Hashing: " + url + "@" + header.getOffset(), i);
    }
}

From source file:org.atombeat.xquery.functions.util.SaveUploadAs.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    RequestModule reqModule = (RequestModule) context.getModule(RequestModule.NAMESPACE_URI);

    // request object is read from global variable $request
    Variable var = reqModule.resolveVariable(RequestModule.REQUEST_VAR);

    if (var == null || var.getValue() == null)
        throw new XPathException(this, "No request object found in the current XQuery context.");

    if (var.getValue().getItemType() != Type.JAVA_OBJECT)
        throw new XPathException(this, "Variable $request is not bound to an Java object.");

    JavaObjectValue value = (JavaObjectValue) var.getValue().itemAt(0);

    if (!(value.getObject() instanceof RequestWrapper)) {
        throw new XPathException(this, "Variable $request is not bound to a Request object.");
    }/*from   w  ww .  j  a  va  2s  .c  om*/

    RequestWrapper request = (RequestWrapper) value.getObject();

    // try to copy upload
    try {
        String paramName = args[0].getStringValue();
        String path = args[1].getStringValue();
        File upload = request.getFileUploadParam(paramName);
        File file = new File(path);
        InputStream in = new FileInputStream(upload);
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        in = new DigestInputStream(in, md5);
        OutputStream out = new FileOutputStream(file);

        Stream.copy(in, out);

        String signature = new BigInteger(1, md5.digest()).toString(16);
        return new StringValue(signature);

    } catch (IOException ioe) {
        throw new XPathException(this, "An IO exception ocurred: " + ioe.getMessage(), ioe);
    } catch (NoSuchAlgorithmException e) {
        throw new XPathException(this, "A message digest exception ocurred: " + e.getMessage(), e);
    }

}