· 7 years ago · May 05, 2018, 03:14 PM
1import java.io.BufferedInputStream;
2import java.io.FileInputStream;
3import java.io.IOException;
4import java.security.DigestInputStream;
5import javax.crypto.Mac;
6import java.security.MessageDigest;
7import java.security.NoSuchAlgorithmException;
8import javax.crypto.KeyGenerator;
9import javax.crypto.SecretKey;
10import java.security.InvalidKeyException;
11
12public class TestDigest {
13
14 /**
15 * Generate the MessageDigest from a string
16 * @param the string
17 * @return the digest of the string
18 */
19 public byte[] testMessageDigest(String str)
20 throws NoSuchAlgorithmException
21 {
22 MessageDigest md = MessageDigest.getInstance("MD5");
23 md.update(str.getBytes());
24 return md.digest();
25 }
26
27 public byte[] testMac(String str, SecretKey key)
28 throws NoSuchAlgorithmException, InvalidKeyException
29 {
30 Mac md = Mac.getInstance("HmacMD5");
31 md.init(key);
32 md.update(str.getBytes());
33 return md.doFinal();
34 }
35
36 /**
37 * Generate the MessageDigest of a file
38 * @param the filename
39 * @return the digest of the file
40 */
41 public byte[] testDigestInputStream(String file)
42 throws IOException,NoSuchAlgorithmException
43 {
44 // other values: "SHA", "MD5", "SHA-384", "SHA-512", "MD2"
45 MessageDigest md = MessageDigest.getInstance("SHA");
46
47 BufferedInputStream in =
48 new BufferedInputStream(
49 new DigestInputStream(
50 new FileInputStream(file),md));
51
52 int c;
53
54 while((c = in.read()) != -1);
55
56 return md.digest();
57 }
58
59 /**
60 * Print a byte array in hexadecimal form
61 * @param the byte array
62 */
63 public static void printHexadecimal(byte[] bytes)
64 {
65 for(int i=0; i<bytes.length; i++)
66 System.out.printf("%X",bytes[i]);
67 }
68
69 public static void main(String args[]) throws Exception
70 {
71 String fileTest = "/etc/passwd";
72 String stringTest = "How can I believe in God when just last week I " +
73 "got my tongue caught in the roller of an electric typewriter?";
74
75 TestDigest td = new TestDigest();
76
77 // Print the digest of a test string
78 System.out.print("String: " + stringTest +"\n" + "String Digest:");
79 td.printHexadecimal(td.testMessageDigest(stringTest));
80 System.out.println();
81
82 // Print the digest of a test file
83 System.out.print("File: " + fileTest +"\n" + "File Digest:");
84 td.printHexadecimal(td.testDigestInputStream(fileTest));
85 System.out.println();
86
87 // Print the digest of a test file
88 System.out.print("File MAC:");
89 KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
90 SecretKey key = keyGen.generateKey();
91 System.out.println("Key:");
92 printHexadecimal(key.getEncoded());
93 System.out.println();
94
95 System.out.println("MAC:");
96 td.printHexadecimal(td.testMac(stringTest,key));
97 System.out.println();
98
99 }
100}