Hash.java
 1 /*
 2  * Hash.java
 3  *
 4  * creates a Message Digest with SHA-1 Algorithm 
 5  *
 6  * based on example "Listing 4803" in "Handbuch der Java Programmierung"
 7  * modified by Alexander Scheidl
 8  * 
 9  */
10 
11 package testrsa;
12 
13 
14 import java.io.*;
15 import java.security.*;
16 
17 public class Hash
18 {
19   
20    /**
21     * converts a byte in a hex-string
22     * 
23     * handels the createHash method
24     *
25     * @param b byte to convert into hex
26     * @return ret string to conv
27     *
28     */
29   public static String toHexString(byte b)
30   {
31     int value = (b & 0x7F) + (b < 0 ? 128 : 0); // 0 to 255 Ascii Code
32     String ret = (value < 16 ? "0" : "");
33     ret += Integer.toHexString(value).toUpperCase();
34     return ret;
35   }
36   
37    /**
38     * Method to convert a Sting into a "Hex-Hash-String"
39     *
40     * uses the MessageDigest method to create a Hash
41     * 
42     * @param data string to convert
43     * @return strbuf String of the Hash Code
44     */
45   
46   public String createHash(String data) throws NoSuchAlgorithmException 
47    { 
48      
49     MessageDigest md = MessageDigest.getInstance("SHA-1");
50     StringBuffer strbuf = new StringBuffer(); 
51     
52           
53     md.update(data.getBytes(), 0, data.length());      
54     byte[] digest; 
55     digest = md.digest(); 
56                 
57           
58     for (int i = 0; i < digest.length; i++) { 
59         strbuf.append(toHexString(digest[i])); 
60      } 
61           
62     return strbuf.toString();      
63    } 
64 
65   
66 }
67