001package algs34;
002import stdlib.*;
003import java.io.UnsupportedEncodingException;
004import java.security.MessageDigest;
005/* ***********************************************************************
006 *  Compilation:  javac OneWay.java
007 *  Execution:    java OneWay password
008 *
009 *  Compute the SHA1 of the command line argument.
010 *
011 *
012 * % java OneWay "The quick brown fox jumps over the lazy dog"
013 * 2fd4e1c6 7a2d28fc ed849ee1 bb76e739 1b93eb12
014 *
015 *  % java OneWay test
016 *  a94a8fe5 ccb19ba6 1c4c0873 d391e987 982fbbd3
017 *
018 *  % java OneWay ""
019 *  da39a3ee 5e6b4b0d 3255bfef 95601890 afd80709
020 *
021 *************************************************************************/
022import java.security.NoSuchAlgorithmException;
023
024public class XOneWay {
025
026        public static void main(String[] args) {
027                args = new String[] { "test" };
028                args = new String[] { "test1" };
029                //args = new String[] { "The quick brown fox jumps over the lazy dog" };
030
031                // get the sha1 encoding object
032                MessageDigest sha1;
033                try { sha1 = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { StdOut.println(e); return; }
034
035                // get the input string as a byte array
036                String password = args[0];
037                byte[] input;
038                try { input = password.getBytes("ISO-8859-1"); } catch (UnsupportedEncodingException e) { StdOut.println(e); return; }
039
040                // perform the conversion
041                byte[] hash = sha1.digest(input);
042
043                // print bytes as hex, careful to handle leading 0s and 2s complement
044                StdOut.print(hash.length + ": " + password.hashCode () + ":");
045                String hex = "0123456789abcdef";
046                for (int i = 0; i < hash.length; i++) {
047                        if (i % 4 == 0) StdOut.print(" ");
048                        StdOut.print(hex.charAt((hash[i] & 0xF0) >> 4));
049                        StdOut.print(hex.charAt((hash[i] & 0x0F) >> 0));
050                }
051                StdOut.println();
052        }
053
054
055}