Digest.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.codec.cli;

  18. import java.io.File;
  19. import java.io.IOException;
  20. import java.nio.charset.Charset;
  21. import java.security.MessageDigest;
  22. import java.util.Arrays;
  23. import java.util.Locale;

  24. import org.apache.commons.codec.binary.Hex;
  25. import org.apache.commons.codec.digest.DigestUtils;
  26. import org.apache.commons.codec.digest.MessageDigestAlgorithms;

  27. /**
  28.  * A minimal command line to run digest over files, directories or a string
  29.  *
  30.  * @see #main(String[])
  31.  * @since 1.11
  32.  */
  33. public class Digest {

  34.     /**
  35.      * Runs the digest algorithm in {@code args[0]} on the file in {@code args[1]}. If there is no {@code args[1]}, use
  36.      * standard input.
  37.      *
  38.      * <p>
  39.      * The algorithm can also be {@code ALL} or {@code *} to output one line for each known algorithm.
  40.      * </p>
  41.      *
  42.      * @param args
  43.      *            {@code args[0]} is one of {@link MessageDigestAlgorithms} name,
  44.      *            {@link MessageDigest} name, {@code ALL}, or {@code *}.
  45.      *            {@code args[1+]} is a FILE/DIRECTORY/String.
  46.      * @throws IOException if an error occurs
  47.      */
  48.     public static void main(final String[] args) throws IOException {
  49.         new Digest(args).run();
  50.     }

  51.     private final String algorithm;
  52.     private final String[] args;
  53.     private final String[] inputs;

  54.     private Digest(final String[] args) {
  55.         if (args == null) {
  56.             throw new IllegalArgumentException("args");
  57.         }
  58.         if (args.length == 0) {
  59.             throw new IllegalArgumentException(
  60.                     String.format("Usage: java %s [algorithm] [FILE|DIRECTORY|string] ...", Digest.class.getName()));
  61.         }
  62.         this.args = args;
  63.         algorithm = args[0];
  64.         if (args.length <= 1) {
  65.             inputs = null;
  66.         } else {
  67.             inputs = new String[args.length -1];
  68.             System.arraycopy(args, 1, inputs, 0, inputs.length);
  69.         }
  70.     }

  71.     private void println(final String prefix, final byte[] digest) {
  72.         println(prefix, digest, null);
  73.     }

  74.     private void println(final String prefix, final byte[] digest, final String fileName) {
  75.         // The standard appears to be to print
  76.         // hex, space, then either space or '*' followed by filename
  77.         // where '*' is used for binary files
  78.         // shasum(1) has a -b option which generates " *" separator
  79.         // we don't distinguish binary files at present
  80.         System.out.println(prefix + Hex.encodeHexString(digest) + (fileName != null ? "  " + fileName : ""));
  81.     }

  82.     private void run() throws IOException {
  83.         if (algorithm.equalsIgnoreCase("ALL") || algorithm.equals("*")) {
  84.             run(MessageDigestAlgorithms.values());
  85.             return;
  86.         }
  87.         final MessageDigest messageDigest = DigestUtils.getDigest(algorithm, null);
  88.         if (messageDigest != null) {
  89.             run("", messageDigest);
  90.         } else {
  91.             run("", DigestUtils.getDigest(algorithm.toUpperCase(Locale.ROOT)));
  92.         }
  93.     }

  94.     private void run(final String[] digestAlgorithms) throws IOException {
  95.         for (final String messageDigestAlgorithm : digestAlgorithms) {
  96.             if (DigestUtils.isAvailable(messageDigestAlgorithm)) {
  97.                 run(messageDigestAlgorithm + " ", messageDigestAlgorithm);
  98.             }
  99.         }
  100.     }

  101.     private void run(final String prefix, final MessageDigest messageDigest) throws IOException {
  102.         if (inputs == null) {
  103.             println(prefix, DigestUtils.digest(messageDigest, System.in));
  104.             return;
  105.         }
  106.         for(final String source : inputs) {
  107.             final File file = new File(source);
  108.             if (file.isFile()) {
  109.                 println(prefix, DigestUtils.digest(messageDigest, file), source);
  110.             } else if (file.isDirectory()) {
  111.                 final File[] listFiles = file.listFiles();
  112.                 if (listFiles != null) {
  113.                     run(prefix, messageDigest, listFiles);
  114.                 }
  115.             } else {
  116.                 // use the default charset for the command-line parameter
  117.                 final byte[] bytes = source.getBytes(Charset.defaultCharset());
  118.                 println(prefix, DigestUtils.digest(messageDigest, bytes));
  119.             }
  120.         }
  121.     }

  122.     private void run(final String prefix, final MessageDigest messageDigest, final File[] files) throws IOException {
  123.         for (final File file : files) {
  124.             if (file.isFile()) {
  125.                 println(prefix, DigestUtils.digest(messageDigest, file), file.getName());
  126.             }
  127.         }
  128.     }

  129.     private void run(final String prefix, final String messageDigestAlgorithm) throws IOException {
  130.         run(prefix, DigestUtils.getDigest(messageDigestAlgorithm));
  131.     }

  132.     @Override
  133.     public String toString() {
  134.         return String.format("%s %s", super.toString(), Arrays.toString(args));
  135.     }
  136. }