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  
56      private final String algorithm;
57      private final String[] args;
58      private final String[] inputs;
59  
60      private Digest(final String[] args) {
61          if (args == null) {
62              throw new IllegalArgumentException("args");
63          }
64          if (args.length == 0) {
65              throw new IllegalArgumentException(
66                      String.format("Usage: java %s [algorithm] [FILE|DIRECTORY|string] ...", Digest.class.getName()));
67          }
68          this.args = args;
69          algorithm = args[0];
70          if (args.length <= 1) {
71              inputs = null;
72          } else {
73              inputs = new String[args.length -1];
74              System.arraycopy(args, 1, inputs, 0, inputs.length);
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 filename
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[] digestAlgorithms) throws IOException {
105         for (final String messageDigestAlgorithm : digestAlgorithms) {
106             if (DigestUtils.isAvailable(messageDigestAlgorithm)) {
107                 run(messageDigestAlgorithm + " ", messageDigestAlgorithm);
108             }
109         }
110     }
111 
112     private void run(final String prefix, final MessageDigest messageDigest) throws IOException {
113         if (inputs == null) {
114             println(prefix, DigestUtils.digest(messageDigest, System.in));
115             return;
116         }
117         for(final String source : inputs) {
118             final File file = new File(source);
119             if (file.isFile()) {
120                 println(prefix, DigestUtils.digest(messageDigest, file), source);
121             } else if (file.isDirectory()) {
122                 final File[] listFiles = file.listFiles();
123                 if (listFiles != null) {
124                     run(prefix, messageDigest, listFiles);
125                 }
126             } else {
127                 // use the default charset for the command-line parameter
128                 final byte[] bytes = source.getBytes(Charset.defaultCharset());
129                 println(prefix, DigestUtils.digest(messageDigest, bytes));
130             }
131         }
132     }
133 
134     private void run(final String prefix, final MessageDigest messageDigest, final File[] files) throws IOException {
135         for (final File file : files) {
136             if (file.isFile()) {
137                 println(prefix, DigestUtils.digest(messageDigest, file), file.getName());
138             }
139         }
140     }
141 
142     private void run(final String prefix, final String messageDigestAlgorithm) throws IOException {
143         run(prefix, DigestUtils.getDigest(messageDigestAlgorithm));
144     }
145 
146     @Override
147     public String toString() {
148         return String.format("%s %s", super.toString(), Arrays.toString(args));
149     }
150 }