KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > james > security > DigestUtil


1 /***********************************************************************
2  * Copyright (c) 2000-2004 The Apache Software Foundation. *
3  * All rights reserved. *
4  * ------------------------------------------------------------------- *
5  * Licensed under the Apache License, Version 2.0 (the "License"); you *
6  * may not use this file except in compliance with the License. You *
7  * 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 *
14  * implied. See the License for the specific language governing *
15  * permissions and limitations under the License. *
16  ***********************************************************************/

17
18 package org.apache.james.security;
19
20 import javax.mail.MessagingException JavaDoc;
21 import javax.mail.internet.MimeUtility JavaDoc;
22 import java.io.*;
23 import java.security.MessageDigest JavaDoc;
24 import java.security.NoSuchAlgorithmException JavaDoc;
25 import java.util.Locale JavaDoc;
26
27
28 /**
29  * Computes and verifies digests of files and strings
30  *
31  *
32  * @version $Revision: 1.6.4.3 $
33  */

34 public class DigestUtil {
35
36     /**
37      * Command line interface. Use -help for arguments.
38      *
39      * @param args the arguments passed in on the command line
40      */

41     public static void main(String JavaDoc[] args) {
42
43         String JavaDoc alg = "SHA";
44         boolean file = false;
45     
46         if (args.length == 0 || args.length > 4) {
47             printUsage();
48             return;
49         }
50     
51         for (int i = 0; i < args.length; i++) {
52             String JavaDoc currArg = args[i].toLowerCase(Locale.US);
53             if (currArg.equals("-help")
54                 || currArg.equals("-usage")) {
55                 printUsage();
56                 return;
57             }
58             if (currArg.equals("-alg")) {
59                 alg = args[i+1];
60             }
61             if (currArg.equals("-file")) {
62                 file = true;
63             }
64         }
65     
66         if (file) {
67             digestFile(args[args.length - 1], alg);
68             return ;
69         } else {
70             try {
71                 String JavaDoc hash = digestString(args[args.length - 1], alg);
72                 System.out.println("Hash is: " + hash);
73                 return;
74             } catch (NoSuchAlgorithmException JavaDoc nsae) {
75                 System.out.println("No such algorithm available");
76             }
77         }
78     }
79
80     /**
81      * Print the command line usage string.
82      */

83     public static void printUsage() {
84         System.out.println("Usage: "
85                            + "java org.apache.james.security.DigestUtil"
86                            + " [-alg algorithm]"
87                            + " [-file] filename|string");
88     }
89
90     /**
91      * Calculate digest of given file with given algorithm.
92      * Writes digest to file named filename.algorithm .
93      *
94      * @param filename the String name of the file to be hashed
95      * @param algorithm the algorithm to be used to compute the digest
96      */

97     public static void digestFile(String JavaDoc filename, String JavaDoc algorithm) {
98         byte[] b = new byte[65536];
99         int count = 0;
100         int read = 0;
101         FileInputStream fis = null;
102         FileOutputStream fos = null;
103         try {
104             MessageDigest JavaDoc md = MessageDigest.getInstance(algorithm);
105             fis = new FileInputStream(filename);
106             while (fis.available() > 0) {
107                 read = fis.read(b);
108                 md.update(b, 0, read);
109                 count += read;
110             }
111             byte[] digest = md.digest();
112             StringBuffer JavaDoc fileNameBuffer =
113                 new StringBuffer JavaDoc(128)
114                         .append(filename)
115                         .append(".")
116                         .append(algorithm);
117             fos = new FileOutputStream(fileNameBuffer.toString());
118             OutputStream encodedStream = MimeUtility.encode(fos, "base64");
119             encodedStream.write(digest);
120             fos.flush();
121         } catch (Exception JavaDoc e) {
122             System.out.println("Error computing Digest: " + e);
123         } finally {
124             try {
125                 fis.close();
126                 fos.close();
127             } catch (Exception JavaDoc ignored) {}
128         }
129     }
130
131     /**
132      * Calculate digest of given String using given algorithm.
133      * Encode digest in MIME-like base64.
134      *
135      * @param pass the String to be hashed
136      * @param algorithm the algorithm to be used
137      * @return String Base-64 encoding of digest
138      *
139      * @throws NoSuchAlgorithmException if the algorithm passed in cannot be found
140      */

141     public static String JavaDoc digestString(String JavaDoc pass, String JavaDoc algorithm )
142             throws NoSuchAlgorithmException JavaDoc {
143
144         MessageDigest JavaDoc md;
145         ByteArrayOutputStream bos;
146
147         try {
148             md = MessageDigest.getInstance(algorithm);
149             byte[] digest = md.digest(pass.getBytes("iso-8859-1"));
150             bos = new ByteArrayOutputStream();
151             OutputStream encodedStream = MimeUtility.encode(bos, "base64");
152             encodedStream.write(digest);
153             return bos.toString("iso-8859-1");
154         } catch (IOException ioe) {
155             throw new RuntimeException JavaDoc("Fatal error: " + ioe);
156         } catch (MessagingException JavaDoc me) {
157             throw new RuntimeException JavaDoc("Fatal error: " + me);
158         }
159     }
160
161     /**
162      * Private constructor to prevent instantiation of the class
163      */

164     private DigestUtil() {}
165 }
166
Popular Tags