Hash generator · Guide

MD5 Hash Android: Generating Digests in Kotlin and Java

Android exposes MD5 through the standard `java.security.MessageDigest`. The API is straightforward; the two things worth getting right are hex formatting and not loading a whole file into memory.

Hashing a string

Specify the charset explicitly. Relying on the platform default is the classic source of digests that differ between devices:

Java
fun md5(input: String): String =
    java.security.MessageDigest.getInstance("MD5")
        .digest(input.toByteArray(Charsets.UTF_8))
        .joinToString("") { "%02x".format(it) }

The %02x format string is what keeps leading zeros. Building hex with Integer.toHexString drops them and produces digests shorter than 32 characters for some inputs — a bug that only shows up occasionally, which makes it hard to spot.

Hashing a file without loading it

Read in chunks and feed the digest incrementally, so memory use stays flat regardless of file size:

Java
fun md5(file: java.io.File): String {
    val digest = java.security.MessageDigest.getInstance("MD5")
    file.inputStream().use { stream ->
        val buffer = ByteArray(8192)
        var read = stream.read(buffer)
        while (read > 0) {
            digest.update(buffer, 0, read)
            read = stream.read(buffer)
        }
    }
    return digest.digest().joinToString("") { "%02x".format(it) }
}

Run this off the main thread — hashing a large file on the UI thread will trigger an ANR.

What not to use it for

MD5 still appears in Android code for cache keys and change detection, which is fine. It also still appears for hashing user passwords and for verifying downloaded APKs, which is not.

Swap the algorithm string to "SHA-256" for anything security-relevant — the surrounding code is identical. For passwords use a KDF, and for APK integrity rely on Android package signing rather than a digest you check yourself.

Frequently asked questions

Why is my hash sometimes 31 characters?

Hex formatting dropped a leading zero. Use "%02x" per byte.

Is MessageDigest thread-safe?

No. Create a new instance per use, or synchronise access.

Does Android have a faster MD5?

MessageDigest is already backed by native code. If hashing is slow, the bottleneck is file I/O, not the algorithm.

Ready to try it?

Open the free browser-based Hash generator and apply what you just read — no sign-up, runs locally.

Open the Hash generator tool