-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathHMACExample.java
More file actions
69 lines (40 loc) · 1.27 KB
/
HMACExample.java
File metadata and controls
69 lines (40 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
Kasun De Zoysa @ UCSC
*/
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
import java.util.*;
public class HMACExample{
public static void main(String args[]) {
try {
String key1 = "MIS@UCSC";
SecretKeySpec sk1 = new SecretKeySpec(key1.getBytes(), "HMACSHA256");
// Create a MAC object using HMAC-MD5 and initialize with key
Mac mac1 = Mac.getInstance("HMACSHA256");
mac1.init(sk1);
String data1 = "Hello kasun";
byte[] digest1 = mac1.doFinal(data1.getBytes());
System.out.println("Orig. HMAC: ");
for(byte b:digest1) System.out.format("%02x",b);
System.out.println("");
//Verification
String key2 = "MIS@UCSC";
SecretKeySpec sk2 = new SecretKeySpec(key2.getBytes(), "HMACSHA256");
Mac mac2 = Mac.getInstance("HMACSHA256");
mac2.init(sk2);
String data2 = "Hello kasun";
byte digest2[] = mac2.doFinal(data2.getBytes());
System.out.println("New HMAC: ");
for(byte b:digest2) System.out.format("%02x",b);
System.out.println("");
if(Arrays.equals(digest1,digest2))
System.out.println("Digest Verified");
else
System.out.println("Digest Verification failed!");
} catch (Exception e) {
System.out.println(e);
}
}
}