Y01.java

import java.security.*;
import java.io.*;

/**
Compute SHA-1 or MD5 message digest of one or more file(s) specified 
on the command line.
*/
class Y01
{
    public static void main(String argv[])
    {
        String algorithm;
        byte[] result;
        int i;

        if (argv.length < 2) {
            System.err.println(
                "You must supply an algorithm " +
                "('SHA-1' or 'MD5') and one or more filenames.");
            System.exit(2);
            }

        algorithm = argv[0].toUpperCase();
        /*
        if (!algorithm.equals("SHA-1") && !algorithm.equals("MD5")) {
            System.err.println(
                "Algorithm name must be 'SHA-1' or 'MD5'.");
            System.exit(2);
            }
        */

        try {
            for (i=1; i<argv.length; i++) {
                result = oneFile(argv[i],algorithm);
                System.out.println(d2s(result) + " -- " + argv[i]);
                }
            }
        catch (IOException e) {
            System.out.println("I/O error: " + e);
            }
        catch (NoSuchAlgorithmException e) {
            System.out.println("Alg error: " + e);
            }
    }

    /**
    Return a message digest (using the specified <code>algorithm</code>)
    of file <code>filename</code>.
    */
    private static byte[] oneFile(String filename,String algorithm)
        throws IOException,NoSuchAlgorithmException
    {
        FileInputStream in;
        MessageDigest d;
        int c,i;

        in = new FileInputStream(filename);
        d = MessageDigest.getInstance(algorithm);

        while ((c = in.read()) != -1)
            d.update((byte)c);
        return d.digest();
    }

    /**
    Hex string representation of byte array.
    */
    private static String d2s(byte[] digest)
    {
        StringBuffer buf = new StringBuffer(50);
        for (int i=0; i<digest.length; i++) {
            //if (i > 0)
            //    buf.append(" ");
            buf.append(hexIt(digest[i]));
            }
        return buf.toString();
    }

    /**
    Return a two-character hex representation of a byte.
    */
    private static String hexIt(byte b)
    {
        int value = (int)b & 0xFF;
        String s = Integer.toHexString(value);
        if (value < 16)
            return "0" + s;
        else
            return s;
    }
}