-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMD5MACExample.java
54 lines (42 loc) · 1.83 KB
/
MD5MACExample.java
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
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException; // Import the InvalidKeyException class
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;
public class MD5MACExample {
public static void main(String[] args) {
try {
// Generate a secret key for the MAC algorithm
Scanner sc=new Scanner(System.in);
String secretKey = sc.nextLine(); // Replace with your secret key
// Message to be authenticated
String message = sc.nextLine();
// Generate MAC for the message using MD5
byte[] mac = generateMD5MAC(secretKey, message.getBytes());
// Print the original message and MAC
System.out.println("Original Message: " + message);
System.out.println("Generated MAC: " + bytesToHex(mac));
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace();
}
}
// Function to generate a MAC for the given message using MD5
private static byte[] generateMD5MAC(String secretKey, byte[] message) throws NoSuchAlgorithmException, InvalidKeyException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] keyBytes = secretKey.getBytes();
Key key = new SecretKeySpec(keyBytes, "HmacMD5");
Mac mac = Mac.getInstance("HmacMD5");
mac.init(key);
return mac.doFinal(message);
}
// Function to convert byte array to hex string for better display
private static String bytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
result.append(String.format("%02x", b));
}
return result.toString();
}
}