View Javadoc
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    *      https://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  
18  package org.apache.commons.codec.cli;
19  
20  import java.io.BufferedInputStream;
21  import java.io.File;
22  import java.io.IOException;
23  import java.nio.charset.Charset;
24  import java.security.MessageDigest;
25  import java.util.Arrays;
26  import java.util.Locale;
27  import java.util.Objects;
28  
29  import org.apache.commons.codec.binary.Hex;
30  import org.apache.commons.codec.digest.DigestUtils;
31  import org.apache.commons.codec.digest.MessageDigestAlgorithms;
32  
33  /**
34   * A minimal command line to run digest over files, directories or a string.
35   *
36   * @see #main(String[])
37   * @since 1.11
38   */
39  public class Digest {
40  
41      private static final String EMPTY = "";
42  
43      /**
44       * Runs the digest algorithm in {@code args[0]} on the file in {@code args[1]}. If there is no {@code args[1]}, use standard input.
45       *
46       * <p>
47       * The algorithm can also be {@code ALL} or {@code *} to output one line for each known algorithm.
48       * </p>
49       *
50       * @param args {@code args[0]} is one of {@link MessageDigestAlgorithms} name, {@link MessageDigest} name, {@code ALL}, or {@code *}. {@code args[1+]} is a
51       *             FILE/DIRECTORY/String.
52       * @throws IOException if an error occurs.
53       */
54      public static void main(final String[] args) throws IOException {
55          new Digest(args).run();
56      }
57  
58      private final String algorithm;
59      private final String[] args;
60      private final String[] inputs;
61  
62      private Digest(final String[] args) {
63          Objects.requireNonNull(args, "args");
64          final int argsLength = args.length;
65          if (argsLength == 0) {
66              throw new IllegalArgumentException(String.format("Usage: java %s [algorithm] [FILE|DIRECTORY|string] ...", Digest.class.getName()));
67          }
68          this.args = args;
69          this.algorithm = args[0];
70          this.inputs = argsLength > 1 ? Arrays.copyOfRange(args, 1, argsLength) : null;
71      }
72  
73      private void println(final String prefix, final byte[] digest) {
74          println(prefix, digest, null);
75      }
76  
77      private void println(final String prefix, final byte[] digest, final String fileName) {
78          // The standard appears to be to print
79          // hex, space, then either space or '*' followed by file name
80          // where '*' is used for binary files
81          // shasum(1) has a -b option which generates " *" separator
82          // we don't distinguish binary files at present
83          System.out.println(prefix + Hex.encodeHexString(digest) + (fileName != null ? "  " + fileName : EMPTY));
84      }
85  
86      private void run() throws IOException {
87          final BufferedInputStream systemIn = inputs != null ? null : new BufferedInputStream(System.in);
88          if (algorithm.equalsIgnoreCase("ALL") || algorithm.equals("*")) {
89              run(systemIn, MessageDigestAlgorithms.values());
90              return;
91          }
92          final MessageDigest messageDigest = DigestUtils.getDigest(algorithm, null);
93          if (messageDigest != null) {
94              run(systemIn, EMPTY, messageDigest);
95          } else {
96              run(systemIn, EMPTY, DigestUtils.getDigest(algorithm.toUpperCase(Locale.ROOT)));
97          }
98      }
99  
100     private void run(final BufferedInputStream systemIn, final String prefix, final MessageDigest messageDigest) throws IOException {
101         if (inputs == null) {
102             println(prefix, DigestUtils.digest(messageDigest, systemIn));
103             return;
104         }
105         for (final String source : inputs) {
106             final File file = new File(source);
107             if (file.isFile()) {
108                 println(prefix, DigestUtils.digest(messageDigest, file), source);
109             } else if (file.isDirectory()) {
110                 final File[] listFiles = file.listFiles();
111                 if (listFiles != null) {
112                     run(prefix, messageDigest, listFiles);
113                 }
114             } else {
115                 // use the default charset for the command-line parameter
116                 final byte[] bytes = source.getBytes(Charset.defaultCharset());
117                 println(prefix, DigestUtils.digest(messageDigest, bytes));
118             }
119         }
120     }
121 
122     private void run(final BufferedInputStream systemIn, final String prefix, final String messageDigestAlgorithm) throws IOException {
123         run(systemIn, prefix, DigestUtils.getDigest(messageDigestAlgorithm));
124     }
125 
126     private void run(final BufferedInputStream systemIn, final String[] digestAlgorithms) throws IOException {
127         for (final String messageDigestAlgorithm : digestAlgorithms) {
128             if (DigestUtils.isAvailable(messageDigestAlgorithm)) {
129                 if (systemIn != null) {
130                     // 1 GB arbitrary default.
131                     systemIn.mark(Integer.getInteger(getClass().getName() + ".markReadLimit", 1_073_741_824));
132                 }
133                 run(systemIn, messageDigestAlgorithm + " ", messageDigestAlgorithm);
134                 if (systemIn != null) {
135                     systemIn.reset();
136                 }
137             }
138         }
139     }
140 
141     private void run(final String prefix, final MessageDigest messageDigest, final File[] files) throws IOException {
142         for (final File file : files) {
143             if (file.isFile()) {
144                 println(prefix, DigestUtils.digest(messageDigest, file), file.getName());
145             }
146         }
147     }
148 
149     @Override
150     public String toString() {
151         return String.format("%s %s", super.toString(), Arrays.toString(args));
152     }
153 }