MD5 Hashing in Java
2.MD5 Using MessageDigest Class
java.security.MessageDigest class:
MessageDigest.getInstance(String Algorithm)
public void update(byte [] input)
public byte[] digest()
generates a hash for a password and then verifies it:
@Test
public void givenPassword_whenHashing_thenVerifying()
throws NoSuchAlgorithmException {
String hash = "35454B055CC325EA1AF2126E27707052";
String password = "ILoveJava";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
byte[] digest = md.digest();
String myHash = DatatypeConverter
.printHexBinary(digest).toUpperCase();
assertThat(myHash.equals(hash)).isTrue();
}
verify checksum of a file:
@Test
public void givenFile_generatingChecksum_thenVerifying()
throws NoSuchAlgorithmException, IOException {
String filename = "src/test/resources/test_md5.txt";
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(Files.readAllBytes(Paths.get(filename)));
byte[] digest = md.digest();
String myChecksum = DatatypeConverter
.printHexBinary(digest).toUpperCase();
assertThat(myChecksum.equals(checksum)).isTrue();
}
MessageDigest is not thread-safe
3.MD5 Using Apache Commons
org.apache.commons.codec.digest.DigestUtils:
@Test
public void givenPassword_whenHashingUsingCommons_thenVerifying() {
String hash = "35454B055CC325EA1AF2126E27707052";
String password = "ILoveJava";
String md5Hex = DigestUtils
.md5Hex(password).toUpperCase();
assertThat(md5Hex.equals(hash)).isTrue();
}
4.MD5 Using Guava
com.google.common.io.Files.hash:
@Test
public void givenFile_whenChecksumUsingGuava_thenVerifying()
throws IOException {
String filename = "src/test/resources/test_md5.txt";
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
HashCode hash = com.google.common.io.Files
.hash(new File(filename), Hashing.md5());
String myChecksum = hash.toString()
.toUpperCase();
assertThat(myChecksum.equals(checksum)).isTrue();
}
we're better off considering safer options, like SHA-256.
https://www.baeldung.com/java-md5