Bastian Ebeling Bastian Ebeling - 1 month ago 19
Java Question

Calculating MD5 Hash (RFC 1321 conform) in Matlab via Java

I want to calculate MD5 (or other) file hashes (RFC 1321 conform) within MATLAB using the Java-Security-Implementations. Thus I coded

mddigest=java.security.MessageDigest.getInstance('MD5');
filestream=java.io.FileInputStream(java.io.File(filename));
digestream=java.security.DigestInputStream(filestream,mddigest);
md5hash=reshape(dec2hex(typecast(mddigest.digest,'uint8')),1,[])


and the routine is working fine. Somehow, the result differs from given tools.

Maybe there are problems with the file-encoding? Should't MATLAB solve that internally?

I'd like to reproduce the results, one gets by md5sum (on linux), which equal those from HashCalc (Windows).

Answer

There is two problems:

  1. You don't read the file.
  2. You have to transpose the matrix before reshape it.

This code works:

mddigest   = java.security.MessageDigest.getInstance('MD5'); 
filestream = java.io.FileInputStream(java.io.File(filename)); 
digestream = java.security.DigestInputStream(filestream,mddigest);

while(digestream.read() ~= -1) end

md5hash=reshape(dec2hex(typecast(mddigest.digest(),'uint8'))',1,[]);