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:pt.webdetails.cpf.Util.java

public static String getMd5Digest(InputStream input) throws IOException {
    try {//ww  w . ja v a 2s .  c o  m
        MessageDigest digest = MessageDigest.getInstance("MD5");
        DigestInputStream digestStream = new DigestInputStream(input, digest);
        IOUtils.copy(digestStream, NullOutputStream.NULL_OUTPUT_STREAM);
        return bytesToHex(digest.digest());
    } catch (NoSuchAlgorithmException e) {
        logger.fatal("No MD5!", e);
        return null;
    }
}

From source file:fi.elfcloud.sci.DataItem.java

/**
 * Stores data to {@link DataItem}// w ww. jav  a2 s  .  c  om
 * @param method the store method used for store operation (<code>new</code> or <code>replace</code>)
 * @param is the data to be sent
 * @throws IOException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws ECException
 * @throws ECEncryptionException
 */
public void storeData(String method, InputStream is) throws IOException, InvalidKeyException,
        InvalidAlgorithmParameterException, ECException, ECEncryptionException {
    Map<String, String> headers = new HashMap<String, String>();
    String meta = "";
    synchronized (this) {
        meta = this.client.createMeta(this.meta);
    }
    headers.put("X-ELFCLOUD-STORE-MODE", method);
    headers.put("X-ELFCLOUD-KEY", Base64.encodeBase64String(this.name.getBytes("UTF-8")));
    headers.put("X-ELFCLOUD-PARENT", Integer.toString(this.parentId));
    headers.put("X-ELFCLOUD-META", meta);
    headers.put("Content-Type", "application/octet-stream");
    MessageDigest ciphermd = null;
    MessageDigest plainmd = null;
    try {
        ciphermd = MessageDigest.getInstance("MD5");
        plainmd = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
    }

    DigestInputStream digestStream = new DigestInputStream(is, plainmd);
    InputStream dataStream;
    if (client.getEncryptionMode() != Client.ENC.NONE) {
        dataStream = new DataStream(Cipher.ENCRYPT_MODE, digestStream, null).getStream();
    } else {
        dataStream = new DataStream(0, digestStream, null).getStream();
    }

    int buffsize = 20971520;
    byte[] buff = new byte[buffsize];
    int len = 0;
    int inbuff = 0;
    while ((len = dataStream.read(buff, 0, buffsize)) > 0) {
        inbuff = len;
        while ((inbuff < buffsize)) {
            len = dataStream.read(buff, inbuff, buffsize - inbuff);
            if (len == -1) {
                break;
            }
            inbuff += len;
        }
        ciphermd.update(buff, 0, inbuff);
        headers.put("Content-Length", Integer.toString(inbuff));
        headers.put("X-ELFCLOUD-HASH", Utils.getHex(ciphermd.digest()));
        this.client.getConnection().sendData(headers, buff, inbuff);
        headers.put("X-ELFCLOUD-STORE-MODE", "append");
    }
    this.meta = meta;
    HashMap<String, String> metamap = Utils.metaToMap(this.meta);
    metamap.put("CHA", Utils.getHex(plainmd.digest()));
    updateMeta(metamap);
}

From source file:org.dcm4chex.archive.hsm.VerifyTar.java

public static Map<String, byte[]> verify(InputStream in, String tarname, byte[] buf,
        ArrayList<String> objectNames) throws IOException, VerifyTarException {
    TarInputStream tar = new TarInputStream(in);
    try {/* www .  jav a2 s. co m*/
        log.debug("Verify tar file: {}", tarname);
        TarEntry entry = tar.getNextEntry();
        if (entry == null)
            throw new VerifyTarException("No entries in " + tarname);
        String entryName = entry.getName();
        if (!"MD5SUM".equals(entryName))
            throw new VerifyTarException("Missing MD5SUM entry in " + tarname);
        BufferedReader dis = new BufferedReader(new InputStreamReader(tar));

        HashMap<String, byte[]> md5sums = new HashMap<String, byte[]>();
        String line;
        while ((line = dis.readLine()) != null) {
            char[] c = line.toCharArray();
            byte[] md5sum = new byte[16];
            for (int i = 0, j = 0; i < md5sum.length; i++, j++, j++) {
                md5sum[i] = (byte) ((fromHexDigit(c[j]) << 4) | fromHexDigit(c[j + 1]));
            }
            md5sums.put(line.substring(34), md5sum);
        }
        Map<String, byte[]> entries = new HashMap<String, byte[]>(md5sums.size());
        entries.putAll(md5sums);
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        while ((entry = tar.getNextEntry()) != null) {
            entryName = entry.getName();
            log.debug("START: Check MD5 of entry: {}", entryName);
            if (objectNames != null && !objectNames.remove(entryName))
                throw new VerifyTarException(
                        "TAR " + tarname + " contains entry: " + entryName + " not in file list");
            byte[] md5sum = (byte[]) md5sums.remove(entryName);
            if (md5sum == null)
                throw new VerifyTarException("Unexpected TAR entry: " + entryName + " in " + tarname);
            digest.reset();
            in = new DigestInputStream(tar, digest);
            while (in.read(buf) > 0)
                ;
            if (!Arrays.equals(digest.digest(), md5sum)) {
                throw new VerifyTarException("Failed MD5 check of TAR entry: " + entryName + " in " + tarname);
            }
            log.debug("DONE: Check MD5 of entry: {}", entryName);
        }
        if (!md5sums.isEmpty())
            throw new VerifyTarException("Missing TAR entries: " + md5sums.keySet() + " in " + tarname);
        if (objectNames != null && !objectNames.isEmpty())
            throw new VerifyTarException(
                    "Missing TAR entries from object list: " + objectNames.toString() + " in " + tarname);
        return entries;
    } finally {
        tar.close();
    }
}

From source file:com.sina.auth.AbstractAWSSigner.java

protected byte[] hash(InputStream input) throws SCSClientException {
    try {//from   w  ww  . ja  v  a  2 s .  co 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:cn.ctyun.amazonaws.auth.AbstractAWSSigner.java

protected byte[] hash(InputStream input) throws AmazonClientException {
    try {/* ww w. ja  va 2 s.  co 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 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  ww w  . ja va 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 LunacloudClientException("Unable to compute hash while signing request: " + e.getMessage(),
                e);
    }
}

From source file:com.microsoftopentechnologies.windowsazurestorage.service.UploadToFileService.java

private String uploadCloudFile(final CloudFile cloudFile, final FilePath localPath) throws WAStorageException {
    try {//from www .  j a  v a2s  .  c  o  m
        ensureDirExist(cloudFile.getParent());
        cloudFile.setMetadata(updateMetadata(cloudFile.getMetadata()));

        final MessageDigest md = DigestUtils.getMd5Digest();
        long startTime = System.currentTimeMillis();
        try (InputStream inputStream = localPath.read();
                DigestInputStream digestInputStream = new DigestInputStream(inputStream, md)) {
            cloudFile.upload(digestInputStream, localPath.length(), null, new FileRequestOptions(),
                    Utils.updateUserAgent());
        }
        long endTime = System.currentTimeMillis();

        println("Uploaded blob with uri " + cloudFile.getUri() + " in " + getTime(endTime - startTime));
        return DatatypeConverter.printHexBinary(md.digest());
    } catch (IOException | InterruptedException | URISyntaxException | StorageException e) {
        throw new WAStorageException("fail to upload file to azure file storage", e);
    }

}

From source file:org.calrissian.mango.jms.stream.AbstractJmsFileTransferSupport.java

@SuppressWarnings("unchecked")
public void sendStream(Request req, final Destination replyTo) throws IOException {

    DigestInputStream is;//  w  w  w  .  j  a  va 2 s.c  o m
    Assert.notNull(req, "Request cannot be null");
    final URI downloadUrl;
    try {
        downloadUrl = new URI(req.getDownloadUri());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    try {

        is = new DigestInputStream(new BufferedInputStream(streamOpener.openStream(downloadUrl)),
                MessageDigest.getInstance(getHashAlgorithm()));

    } catch (NoSuchAlgorithmException e) {
        throw new JmsFileTransferException(e);
    } catch (Throwable e) {

        logger.info("Error occurred opening stream: " + e);
        return;
    }

    MessageQueueListener queueListener = null;
    try {

        @SuppressWarnings("rawtypes")
        Message returnMessage = (Message) jmsTemplate.execute(new SessionCallback() {

            @Override
            public Object doInJms(Session session) throws JMSException {
                DestinationRequestor requestor = null;
                try {
                    Message responseMessage = DomainMessageUtils.toResponseMessage(session,
                            new Response(ResponseStatusEnum.ACCEPT));

                    // Actual file transfer should be done on a queue.
                    // Topics will not work
                    Destination streamTransferDestination = factoryDestination(session,
                            UUID.randomUUID().toString());
                    requestor = new DestinationRequestor(session, replyTo, streamTransferDestination,
                            jmsTemplate.getReceiveTimeout());
                    Message returnMessage = requestor.request(responseMessage);
                    requestor.close();
                    return returnMessage;
                } finally {
                    if (requestor != null)
                        requestor.close();
                }
            }

        }, true);

        // timeout
        if (returnMessage == null)
            return;
        Response response = DomainMessageUtils.fromResponseMessage(returnMessage);

        // cancel transfer
        if (!ResponseStatusEnum.STARTSEND.equals(response.getStatus()))
            return;

        final Destination receiveAckDestination = returnMessage.getJMSDestination();
        final Destination sendDataDestination = returnMessage.getJMSReplyTo();

        queueListener = new MessageQueueListener(this, receiveAckDestination);

        logger.info("Sender[" + req.getRequestId() + "]: Starting send to: " + sendDataDestination);

        byte[] buffer = new byte[getPieceSize()];
        int read = is.read(buffer);
        long placeInFile = 0;
        while (read >= 0) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            stream.write(buffer, 0, read);
            stream.close();
            final byte[] pieceData = stream.toByteArray();
            final Piece piece = new Piece(placeInFile, pieceData, getHashAlgorithm());
            logger.info("Sender[" + req.getRequestId() + "]: Sending piece with position: "
                    + piece.getPosition() + " Size of piece: " + pieceData.length);
            jmsTemplate.send(sendDataDestination, new MessageCreator() {

                @Override
                public Message createMessage(Session session) throws JMSException {
                    return DomainMessageUtils.toPieceMessage(session, piece);
                }

            });
            //                Message ret = jmsTemplate.receive(receiveAckDestination);
            Message ret = queueListener.getMessageInQueue();
            logger.info("Sender[" + req.getRequestId() + "]: Sent piece and got ack");

            // no one on the other end any longer, timeout
            if (ret == null)
                return;

            Response res = DomainMessageUtils.fromResponseMessage(ret);
            // stop transfer
            if (ResponseStatusEnum.RESEND.equals(res.getStatus())) {
                // resend piece
                logger.info("Sender[" + req.getRequestId() + "]: Resending piece");
            } else if (ResponseStatusEnum.DENY.equals(res.getStatus())) {
                return;
            } else {
                buffer = new byte[getPieceSize()];
                placeInFile += read;
                read = is.read(buffer);
            }
        }

        logger.info("Sender[" + req.getRequestId() + "]: Sending stop send");

        final DigestInputStream fiIs = is;

        jmsTemplate.send(sendDataDestination, new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                Response stopSendResponse = new Response(ResponseStatusEnum.STOPSEND);
                stopSendResponse.setHash(new String(fiIs.getMessageDigest().digest()));
                return DomainMessageUtils.toResponseMessage(session, stopSendResponse);
            }

        });

        Message ackMessage = queueListener.getMessageInQueue();

        Object fromMessage = DomainMessageUtils.fromMessage(ackMessage);
        if (fromMessage instanceof Response) {
            Response ackResponse = (Response) fromMessage;
            if (ResponseStatusEnum.RESEND.equals(ackResponse.getStatus())) {
                // TODO: resend the whole file
            }
        }

    } catch (Exception e) {
        throw new JmsFileTransferException(e);
    } finally {
        try {
            is.close();
        } catch (IOException ignored) {
        }
        if (queueListener != null)
            queueListener.close();
    }
}

From source file:org.eclipse.hawkbit.artifact.repository.ArtifactStoreTest.java

private static DigestInputStream digestInputStream(final ByteArrayInputStream stream, final String digest)
        throws NoSuchAlgorithmException {
    return new DigestInputStream(stream, MessageDigest.getInstance(digest));
}

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

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    logger.debug("begin stream request data to file eval");

    logger.debug("access request module from context");
    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  ww  w . ja v a  2 s. com*/

    logger.debug("access wrapped request");
    RequestWrapper request = (RequestWrapper) value.getObject();

    // we have to access the content-length header directly, rather than do request.getContentLength(), in case it's bigger than an int
    String contentLengthHeader = request.getHeader("Content-Length");

    if (contentLengthHeader == null) {
        logger.debug("content length header is null, returning empty sequence");
        return Sequence.EMPTY_SEQUENCE;
    }

    long contentLength = Long.parseLong(contentLengthHeader);
    logger.debug("content length via header: " + contentLength);
    logger.debug("request.getContentLength(): " + request.getContentLength()); // will be -1 if value is greater than an int

    // try to stream request content to file
    try {
        logger.debug("try to stream request data to file...");
        logger.debug("open request input stream");
        InputStream in = request.getInputStream();
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        logger.debug("create digest input stream");
        in = new DigestInputStream(in, md5);
        String path = args[0].getStringValue();
        logger.debug("creating file at path: " + path);
        File file = new File(path);
        logger.debug("creating file output stream");
        FileOutputStream out = new FileOutputStream(file);
        logger.debug("begin streaming data");
        Stream.copy(in, out, contentLength);
        logger.debug("end streaming data");
        logger.debug("create md5 signature");
        String signature = new BigInteger(1, md5.digest()).toString(16);
        logger.debug("return signature");
        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);
    } catch (Exception e) {
        throw new XPathException(this, "An unexpected exception ocurred: " + e.getMessage(), e);
    }

}