KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > snow > crypto > CryptoUtilities


1 package snow.crypto;
2
3 import snow.utils.gui.ProgressModalDialog;
4 import snow.Language.Language;
5
6 import java.io.*;
7 import java.math.*;
8 import java.net.*;
9
10 import java.security.*;
11 import java.security.spec.*;
12 import javax.crypto.spec.*;
13 import javax.crypto.*;
14
15 public final class CryptoUtilities
16 {
17
18   private CryptoUtilities()
19   {
20
21   } // Constructor
22

23
24     public static byte[] hashMD5(byte[] input)
25     {
26        try
27        {
28           MessageDigest md5 = MessageDigest.getInstance("MD5");
29           return md5.digest(input);
30        }
31        catch(Exception JavaDoc e)
32        {
33           throw new RuntimeException JavaDoc(""+e.getMessage());
34        }
35     }
36
37     /** @return the 20 bytes (160 bits) shamir 1 hash of the input bytes
38     */

39     public static byte[] SHA1Hash(byte[] input)
40     {
41        try
42        {
43           MessageDigest md = MessageDigest.getInstance("SHA1");
44           return md.digest(input);
45        }
46        catch(Exception JavaDoc e)
47        {
48           throw new RuntimeException JavaDoc(""+e.getMessage());
49        }
50     }
51
52     /** call from another thread as the EDT
53     */

54     public static byte[] hashSHA1(File file, ProgressModalDialog pd) throws Exception JavaDoc
55     {
56        if(pd!=null)
57        {
58           pd.setProgressBounds( (int) (file.length() / 65536) );
59           pd.start();
60        }
61
62        FileInputStream fis = null;
63        try
64        {
65           fis = new FileInputStream(file);
66           BufferedInputStream bis = new BufferedInputStream(fis);
67           byte[] buf = new byte[65536];
68           MessageDigest md = MessageDigest.getInstance("SHA1");
69           int read = -1;
70           while((read=bis.read(buf))!=-1)
71           {
72              if(pd!=null)
73              {
74                if(pd.wasCancelled()) throw new Exception JavaDoc(Language.translate("Hashcode computation cancelled"));
75              }
76
77              md.update(buf,0,read);
78
79              if(pd!=null)
80              {
81                pd.incrementProgress(1);
82              }
83           }
84           return md.digest();
85        }
86        catch(Exception JavaDoc e)
87        {
88           //throw new RuntimeException(""+e.getMessage());
89
throw e;
90        }
91        finally
92        {
93           if(fis!=null) try{ fis.close(); } catch(Exception JavaDoc ignore) {}
94        }
95     }
96
97 } // CryptoUtilities
Popular Tags