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