forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMD5.java
73 lines (60 loc) · 2.57 KB
/
MD5.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.thealgorithms.hashes;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
/**
* The MD5 class provides a method to generate the MD5 hash for a given string.
* MD5 (Message Digest Algorithm 5) is a widely used cryptographic hash function that produces
* a 128-bit (16-byte) hash value. It is commonly used for checksums and data integrity,
* although it is no longer considered secure for cryptographic purposes.
*
* @see <a href="https://en.wikipedia.org/wiki/MD5">MD5 on Wikipedia</a>
*/
public class MD5 {
/**
* Generates the MD5 hash of the input string.
*
* @param input the string to be hashed
* @return the MD5 hash as a hexadecimal string
*/
public static String getMd5(String input) {
try {
// Create a MessageDigest instance for MD5
MessageDigest md = MessageDigest.getInstance("MD5");
// Compute the MD5 digest of the input string
byte[] messageDigest = md.digest(input.getBytes());
// Convert the byte array into a BigInteger to get the hash in hexadecimal format
BigInteger no = new BigInteger(1, messageDigest);
// Convert the BigInteger to a hexadecimal string
String hashtext = no.toString(16);
// Pad with leading zeros to ensure the hash is 32 characters long
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
// Return the generated MD5 hash
return hashtext;
} catch (NoSuchAlgorithmException e) {
// Handle the case where MD5 algorithm is not available
throw new RuntimeException(e);
}
}
/**
* The main method that takes user input, computes its MD5 hash, and prints the result.
*
* @param args command-line arguments
* @throws NoSuchAlgorithmException if the MD5 algorithm is not available
*/
public static void main(String args[]) throws NoSuchAlgorithmException {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a string to hash
System.out.print("Enter the string to hash: ");
// Read the input string from the user
String s = scanner.nextLine();
// Compute the MD5 hash of the input string and print it
System.out.println("Your HashCode Generated by MD5 is: " + getMd5(s));
// Close the Scanner object
scanner.close();
}
}