Below is a complete Java 21 example that shows how to compute the eD2k (eDonkey2000) hash of a file. It uses Bouncy-Castle’s lightweight API for the MD4 implementation.
- Add the Bouncy-Castle dependency to your build (here with Maven coordinates):
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.77</version> <!-- or latest -->
</dependency>
- The code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.bouncycastle.crypto.digests.MD4Digest;
import org.bouncycastle.util.encoders.Hex;
public class Ed2kHasher {
/**
* eD2k chunk size is 9500 KiB = 9500 * 1024 bytes = 9_728_000 bytes.
*/
private static final int CHUNK_SIZE = 9_728_000;
/**
* Compute eD2k hash of a file.
* If the file is <= CHUNK_SIZE, it's just MD4(file).
* Otherwise: split into chunks, MD4 each chunk, then MD4(concat(chunkHashes)).
*/
public static String computeEd2kHash(Path filePath) throws IOException {
File file = filePath.toFile();
long fileSize = file.length();
List<byte[]> chunkHashes = new ArrayList<>();
try (FileInputStream in = new FileInputStream(file)) {
byte[] buffer = new byte[CHUNK_SIZE];
int read;
while ((read = in.read(buffer)) > 0) {
MD4Digest md4 = new MD4Digest();
md4.update(buffer, 0, read);
byte[] digest = new byte[md4.getDigestSize()];
md4.doFinal(digest, 0);
chunkHashes.add(digest);
}
}
// If only one chunk, that's the final hash:
if (chunkHashes.size() == 1) {
return Hex.toHexString(chunkHashes.get(0));
}
// Otherwise, MD4 over the concatenation of all chunk-hashes:
MD4Digest finalMd4 = new MD4Digest();
for (byte[] ch : chunkHashes) {
finalMd4.update(ch, 0, ch.length);
}
byte[] finalDigest = new byte[finalMd4.getDigestSize()];
finalMd4.doFinal(finalDigest, 0);
return Hex.toHexString(finalDigest);
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java Ed2kHasher /path/to/file");
System.exit(1);
}
try {
String ed2k = computeEd2kHash(Path.of(args[0]));
System.out.println("eD2k Hash: " + ed2k);
} catch (IOException ex) {
System.err.println("IO error: " + ex.getMessage());
ex.printStackTrace();
}
}
}
Explanation of the key parts:
- We read the input file in consecutive 9 728 000-byte chunks (that’s 9500 KiB).
- For each chunk, we create a fresh
MD4Digest, feed it the bytes, and finalize it into a 16-byte digest.
- If the file is only one chunk long, that chunk’s MD4 is the eD2k hash.
- Otherwise we MD4 the concatenation of all chunk-digests to get the final eD2k-hash.
- We finally hex-encode the 16-byte result (lower-case hex).
Make sure you have added Bouncy-Castle to your classpath (or module path) so that org.bouncycastle.crypto.digests.MD4Digest is available.