---
title: "How do you create an MD5 hash in Java?"
description: "Use MessageDigest.getInstance MD5, then hex-encode the bytes. MD5 is fine for checksums but not for passwords or security, where SHA-256 or bcrypt is better."
url: "https://bugsee.com/answers/java/java-md5-hash/"
---

# How do you create an MD5 hash in Java?

Call `MessageDigest.getInstance("MD5").digest(bytes)` and convert the result to hex. Use MD5 only for checksums, not for passwords or anything security related.

```java
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;   // Java 17+

static String md5(String input) throws Exception {
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
    return HexFormat.of().formatHex(digest);   // 32 hex characters
}

// Before Java 17
StringBuilder sb = new StringBuilder();
for (byte b : digest) sb.append(String.format("%02x", b));
```

MD5 is broken for security purposes because collisions can be created on purpose. Use `SHA-256` (the same API with a different name) for integrity checks, and a password hash such as bcrypt, scrypt or Argon2 for passwords.

## Related questions

- [How do you read a whole file into memory with Files.readAllBytes in Java?](https://bugsee.com/answers/java/files-readallbytes/)
