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