MessageDigestInputStream.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.io.input;

  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.security.MessageDigest;
  21. import java.security.NoSuchAlgorithmException;
  22. import java.util.Arrays;
  23. import java.util.Objects;

  24. /**
  25.  * This class is an example for using an {@link ObservableInputStream}. It creates its own {@link org.apache.commons.io.input.ObservableInputStream.Observer},
  26.  * which calculates a checksum using a {@link MessageDigest}, for example, a SHA-512 sum.
  27.  * <p>
  28.  * To build an instance, use {@link Builder}.
  29.  * </p>
  30.  * <p>
  31.  * See the MessageDigest section in the <a href= "https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#MessageDigest"> Java
  32.  * Cryptography Architecture Standard Algorithm Name Documentation</a> for information about standard algorithm names.
  33.  * </p>
  34.  * <p>
  35.  * You must specify a message digest algorithm name or instance.
  36.  * </p>
  37.  * <p>
  38.  * <em>Note</em>: Neither {@link ObservableInputStream}, nor {@link MessageDigest}, are thread safe, so is {@link MessageDigestInputStream}.
  39.  * </p>
  40.  *
  41.  * @see Builder
  42.  * @since 2.15.0
  43.  */
  44. public final class MessageDigestInputStream extends ObservableInputStream {

  45.     // @formatter:off
  46.     /**
  47.      * Builds new {@link MessageDigestInputStream}.
  48.      *
  49.      * <p>
  50.      * For example:
  51.      * </p>
  52.      * <pre>{@code
  53.      * MessageDigestInputStream s = MessageDigestInputStream.builder()
  54.      *   .setPath(path)
  55.      *   .setMessageDigest("SHA-512")
  56.      *   .get();}
  57.      * </pre>
  58.      * <p>
  59.      * You must specify a message digest algorithm name or instance.
  60.      * </p>
  61.      * <p>
  62.      * <em>The MD5 cryptographic algorithm is weak and should not be used.</em>
  63.      * </p>
  64.      *
  65.      * @see #get()
  66.      */
  67.     // @formatter:on
  68.     public static class Builder extends AbstractBuilder<Builder> {

  69.         /**
  70.          * No default by design, call MUST set one.
  71.          */
  72.         private MessageDigest messageDigest;

  73.         /**
  74.          * Constructs a new builder of {@link MessageDigestInputStream}.
  75.          */
  76.         public Builder() {
  77.             // empty
  78.         }

  79.         /**
  80.          * Builds new {@link MessageDigestInputStream}.
  81.          * <p>
  82.          * You must set an aspect that supports {@link #getInputStream()}, otherwise, this method throws an exception.
  83.          * </p>
  84.          * <p>
  85.          * This builder uses the following aspects:
  86.          * </p>
  87.          * <ul>
  88.          * <li>{@link #getInputStream()} gets the target aspect.</li>
  89.          * <li>{@link MessageDigest}</li>
  90.          * </ul>
  91.          *
  92.          * @return a new instance.
  93.          * @throws NullPointerException if messageDigest is null.
  94.          * @throws IllegalStateException         if the {@code origin} is {@code null}.
  95.          * @throws UnsupportedOperationException if the origin cannot be converted to an {@link InputStream}.
  96.          * @throws IOException                   if an I/O error occurs converting to an {@link InputStream} using {@link #getInputStream()}.
  97.          * @see #getInputStream()
  98.          * @see #getUnchecked()
  99.          */
  100.         @Override
  101.         public MessageDigestInputStream get() throws IOException {
  102.             setObservers(Arrays.asList(new MessageDigestMaintainingObserver(messageDigest)));
  103.             return new MessageDigestInputStream(this);
  104.         }

  105.         /**
  106.          * Sets the message digest.
  107.          * <p>
  108.          * <em>The MD5 cryptographic algorithm is weak and should not be used.</em>
  109.          * </p>
  110.          *
  111.          * @param messageDigest the message digest.
  112.          * @return {@code this} instance.
  113.          */
  114.         public Builder setMessageDigest(final MessageDigest messageDigest) {
  115.             this.messageDigest = messageDigest;
  116.             return this;
  117.         }

  118.         /**
  119.          * Sets the name of the name of the message digest algorithm.
  120.          * <p>
  121.          * <em>The MD5 cryptographic algorithm is weak and should not be used.</em>
  122.          * </p>
  123.          *
  124.          * @param algorithm the name of the algorithm. See the MessageDigest section in the
  125.          *                  <a href= "https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#MessageDigest"> Java Cryptography
  126.          *                  Architecture Standard Algorithm Name Documentation</a> for information about standard algorithm names.
  127.          * @return {@code this} instance.
  128.          * @throws NoSuchAlgorithmException if no Provider supports a MessageDigestSpi implementation for the specified algorithm.
  129.          */
  130.         public Builder setMessageDigest(final String algorithm) throws NoSuchAlgorithmException {
  131.             this.messageDigest = MessageDigest.getInstance(algorithm);
  132.             return this;
  133.         }

  134.     }

  135.     /**
  136.      * Maintains the message digest.
  137.      */
  138.     public static class MessageDigestMaintainingObserver extends Observer {

  139.         private final MessageDigest messageDigest;

  140.         /**
  141.          * Constructs an MessageDigestMaintainingObserver for the given MessageDigest.
  142.          *
  143.          * @param messageDigest the message digest to use
  144.          * @throws NullPointerException if messageDigest is null.
  145.          */
  146.         public MessageDigestMaintainingObserver(final MessageDigest messageDigest) {
  147.             this.messageDigest = Objects.requireNonNull(messageDigest, "messageDigest");
  148.         }

  149.         @Override
  150.         public void data(final byte[] input, final int offset, final int length) throws IOException {
  151.             messageDigest.update(input, offset, length);
  152.         }

  153.         @Override
  154.         public void data(final int input) throws IOException {
  155.             messageDigest.update((byte) input);
  156.         }
  157.     }

  158.     /**
  159.      * Constructs a new {@link Builder}.
  160.      *
  161.      * @return a new {@link Builder}.
  162.      */
  163.     public static Builder builder() {
  164.         return new Builder();
  165.     }

  166.     /**
  167.      * A non-null MessageDigest.
  168.      */
  169.     private final MessageDigest messageDigest;

  170.     /**
  171.      * Constructs a new instance, which calculates a signature on the given stream, using the given {@link MessageDigest}.
  172.      * <p>
  173.      * The MD5 cryptographic algorithm is weak and should not be used.
  174.      * </p>
  175.      *
  176.      * @param builder A builder use to get the stream to calculate the message digest and the message digest to use
  177.      * @throws NullPointerException if messageDigest is null.
  178.      */
  179.     private MessageDigestInputStream(final Builder builder) throws IOException {
  180.         super(builder);
  181.         this.messageDigest = Objects.requireNonNull(builder.messageDigest, "builder.messageDigest");
  182.     }

  183.     /**
  184.      * Gets the {@link MessageDigest}, which is being used for generating the checksum, never null.
  185.      * <p>
  186.      * <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
  187.      * data has been read, if that is what you want. The easiest way to do so is by invoking {@link #consume()}.
  188.      * </p>
  189.      *
  190.      * @return the message digest used, never null.
  191.      */
  192.     public MessageDigest getMessageDigest() {
  193.         return messageDigest;
  194.     }
  195. }