    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      https://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.io.input;
    018
    019import java.io.IOException;
    020import java.io.InputStream;
    021import java.security.MessageDigest;
    022import java.security.NoSuchAlgorithmException;
    023import java.util.Arrays;
    024import java.util.Objects;
    025
    026/**
    027 * This class is an example for using an {@link ObservableInputStream}. It creates its own {@link org.apache.commons.io.input.ObservableInputStream.Observer},
    028 * which calculates a checksum using a {@link MessageDigest}, for example, a SHA-512 sum.
    029 * <p>
    030 * To build an instance, use {@link Builder}.
    031 * </p>
    032 * <p>
    033 * See the MessageDigest section in the <a href= "https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#MessageDigest"> Java
    034 * Cryptography Architecture Standard Algorithm Name Documentation</a> for information about standard algorithm names.
    035 * </p>
    036 * <p>
    037 * You must specify a message digest algorithm name or instance.
    038 * </p>
    039 * <p>
    040 * <em>Note</em>: Neither {@link ObservableInputStream}, nor {@link MessageDigest}, are thread safe, so is {@link MessageDigestInputStream}.
    041 * </p>
    042 *
    043 * @see Builder
    044 * @since 2.15.0
    045 */
    046public final class MessageDigestInputStream extends ObservableInputStream {
    047
    048    // @formatter:off
    049    /**
    050     * Builds new {@link MessageDigestInputStream}.
    051     *
    052     * <p>
    053     * For example:
    054     * </p>
    055     * <pre>{@code
    056     * MessageDigestInputStream s = MessageDigestInputStream.builder()
    057     *   .setPath(path)
    058     *   .setMessageDigest("SHA-512")
    059     *   .get();}
    060     * </pre>
    061     * <p>
    062     * You must specify a message digest algorithm name or instance.
    063     * </p>
    064     * <p>
    065     * <em>The MD5 cryptographic algorithm is weak and should not be used.</em>
    066     * </p>
    067     *
    068     * @see #get()
    069     */
    070    // @formatter:on
    071    public static class Builder extends AbstractBuilder<Builder> {
    072
    073        /**
    074         * No default by design, call MUST set one.
    075         */
    076        private MessageDigest messageDigest;
    077
    078        /**
    079         * Constructs a new builder of {@link MessageDigestInputStream}.
    080         */
    081        public Builder() {
    082            // empty
    083        }
    084
    085        /**
    086         * Builds new {@link MessageDigestInputStream}.
    087         * <p>
    088         * You must set an aspect that supports {@link #getInputStream()}, otherwise, this method throws an exception.
    089         * </p>
    090         * <p>
    091         * This builder uses the following aspects:
    092         * </p>
    093         * <ul>
    094         * <li>{@link #getInputStream()} gets the target aspect.</li>
    095         * <li>{@link MessageDigest}</li>
    096         * </ul>
    097         *
    098         * @return a new instance.
    099         * @throws NullPointerException if messageDigest is null.
    100         * @throws IllegalStateException         if the {@code origin} is {@code null}.
    101         * @throws UnsupportedOperationException if the origin cannot be converted to an {@link InputStream}.
    102         * @throws IOException                   if an I/O error occurs converting to an {@link InputStream} using {@link #getInputStream()}.
    103         * @see #getInputStream()
    104         * @see #getUnchecked()
    105         */
    106        @Override
    107        public MessageDigestInputStream get() throws IOException {
    108            setObservers(Arrays.asList(new MessageDigestMaintainingObserver(messageDigest)));
    109            return new MessageDigestInputStream(this);
    110        }
    111
    112        /**
    113         * Sets the message digest.
    114         * <p>
    115         * <em>The MD5 cryptographic algorithm is weak and should not be used.</em>
    116         * </p>
    117         *
    118         * @param messageDigest the message digest.
    119         * @return {@code this} instance.
    120         */
    121        public Builder setMessageDigest(final MessageDigest messageDigest) {
    122            this.messageDigest = messageDigest;
    123            return this;
    124        }
    125
    126        /**
    127         * Sets the name of the name of the message digest algorithm.
    128         * <p>
    129         * <em>The MD5 cryptographic algorithm is weak and should not be used.</em>
    130         * </p>
    131         *
    132         * @param algorithm the name of the algorithm. See the MessageDigest section in the
    133         *                  <a href= "https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#MessageDigest"> Java Cryptography
    134         *                  Architecture Standard Algorithm Name Documentation</a> for information about standard algorithm names.
    135         * @return {@code this} instance.
    136         * @throws NoSuchAlgorithmException if no Provider supports a MessageDigestSpi implementation for the specified algorithm.
    137         */
    138        public Builder setMessageDigest(final String algorithm) throws NoSuchAlgorithmException {
    139            this.messageDigest = MessageDigest.getInstance(algorithm);
    140            return this;
    141        }
    142
    143    }
    144
    145    /**
    146     * Maintains the message digest.
    147     */
    148    public static class MessageDigestMaintainingObserver extends Observer {
    149
    150        private final MessageDigest messageDigest;
    151
    152        /**
    153         * Constructs an MessageDigestMaintainingObserver for the given MessageDigest.
    154         *
    155         * @param messageDigest the message digest to use.
    156         * @throws NullPointerException if messageDigest is null.
    157         */
    158        public MessageDigestMaintainingObserver(final MessageDigest messageDigest) {
    159            this.messageDigest = Objects.requireNonNull(messageDigest, "messageDigest");
    160        }
    161
    162        @Override
    163        public void data(final byte[] input, final int offset, final int length) throws IOException {
    164            messageDigest.update(input, offset, length);
    165        }
    166
    167        @Override
    168        public void data(final int input) throws IOException {
    169            messageDigest.update((byte) input);
    170        }
    171    }
    172
    173    /**
    174     * Constructs a new {@link Builder}.
    175     *
    176     * @return a new {@link Builder}.
    177     */
    178    public static Builder builder() {
    179        return new Builder();
    180    }
    181
    182    /**
    183     * A non-null MessageDigest.
    184     */
    185    private final MessageDigest messageDigest;
    186
    187    /**
    188     * Constructs a new instance, which calculates a signature on the given stream, using the given {@link MessageDigest}.
    189     * <p>
    190     * The MD5 cryptographic algorithm is weak and should not be used.
    191     * </p>
    192     *
    193     * @param builder A builder use to get the stream to calculate the message digest and the message digest to use.
    194     * @throws NullPointerException if messageDigest is null.
    195     */
    196    private MessageDigestInputStream(final Builder builder) throws IOException {
    197        super(builder);
    198        this.messageDigest = Objects.requireNonNull(builder.messageDigest, "builder.messageDigest");
    199    }
    200
    201    /**
    202     * Gets the {@link MessageDigest}, which is being used for generating the checksum, never null.
    203     * <p>
    204     * <em>Note</em>: The checksum will only reflect the data, which has been read so far. This is probably not, what you expect. Make sure, that the complete
    205     * data has been read, if that is what you want. The easiest way to do so is by invoking {@link #consume()}.
    206     * </p>
    207     *
    208     * @return the message digest used, never null.
    209     */
    210    public MessageDigest getMessageDigest() {
    211        return messageDigest;
    212    }
    213}