All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.nuiton.util.MD5InputStream Maven / Gradle / Ivy

There is a newer version: 3.1
Show newest version
/*
 * #%L
 * Nuiton Utils
 * %%
 * Copyright (C) 2004 - 2010 CodeLutin
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as 
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public 
 * License along with this program.  If not, see
 * .
 * #L%
 */

package org.nuiton.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import static org.nuiton.i18n.I18n.t;

/**
 * MD5InputStream, a subclass of FilterInputStream implementing MD5
 * functionality on a stream.
 *
 * @author Tony Chemit - [email protected]
 */
public class MD5InputStream extends DigestInputStream {

    /** Class logger. */
    private static final Log log = LogFactory.getLog(MD5InputStream.class);

    protected static MessageDigest getMD5Digest() throws IllegalStateException {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            return digest;
        } catch (NoSuchAlgorithmException e) {
            if (log.isErrorEnabled()) {
                log.error(t("nuitonutil.error.could.not.find.MD5"), e);
            }
            throw new IllegalStateException(e);
        }
    }

    /**
     * Compute the MD5 for the given {@code input}.
     *
     * Note: The the stream will be closed after calling the method
     * even if something was wrong.
     *
     * @param input the stream to parse
     * @return the MD5 hash for the given input stream
     * @throws IOException if any pb while reading in stream or digest
     */
    public static byte[] hash(InputStream input) throws IOException {
        MD5InputStream in = new MD5InputStream(input);
        try {
            while (in.read() != -1) {
                // read a caracter on stream
            }

            byte[] result = in.hash();
            return result;
        } finally {
            in.close();
        }
    }


    /**
     * Compute the MD5 for the given {@code input} file.
     *
     * @param input the File stream to parse
     * @return the MD5 hash for the given input File
     * @throws IOException if any pb while reading in stream or digest
     */
    public static byte[] hash(File input) throws IOException {
        InputStream inputStream = new BufferedInputStream(new FileInputStream(input));
        byte[] result;
        try {
            result = hash(inputStream);
        } finally {
            inputStream.close();
        }
        return result;
    }


    /**
     * Compute the MD5 for the given {@code input} sring.
     *
     * @param input the stream to parse
     * @return the MD5 hash for the given input String
     * @throws IOException if any pb while reading in stream or digest
     */
    public static byte[] hash(String input) throws IOException {
        byte[] result = hash(new ByteArrayInputStream(input.getBytes()));
        return result;
    }

    /** length of readed stream */
    protected long streamLength;

    /**
     * Creates a MD5InputStream
     *
     * @param in The input stream
     */
    public MD5InputStream(InputStream in) {
        super(in, getMD5Digest());
    }

    @Override
    public int read() throws IOException {
        int c = super.read();

        if (c == -1) {
            return -1;
        }
        streamLength++;
        return c;
    }

    @Override
    public int read(byte bytes[], int offset, int length) throws IOException {
        int r;

        if ((r = super.read(bytes, offset, length)) == -1) {
            return r;
        }
        streamLength += r;
        return r;
    }

    /**
     * Returns array of bytes representing hash of the stream as finalized for
     * the current state.
     *
     * @return hash
     * @see MessageDigest#digest()
     */
    public byte[] hash() {
        return getMessageDigest().digest();
    }

    public long getStreamLength() {
        return streamLength;
    }
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy