Calculating MD5 hash (RFC 1321 compliant) in Matlab via Java

I want to calculate the hashes of MD5 files (or others) ( RFC 1321 ) in MATLAB using Java-Security-Implementations. So 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 procedure is working fine. One way or another, the result is different from the given tools.
Maybe there are problems with the encoding of files? Should MATLAB solve this internally?
I would like to reproduce the results, get md5sum (on linux) that are equal to those from HashCalc (Windows).

+5
source share
3 answers

There are two problems:

  • You do not read the file.
  • You must migrate the matrix before changing 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,[]);

/!\ : p.vitzliputzli , .

+6

DigestInputStream.

, .

( DigestInputStream), digest, .

+2

Stephane , - MATLAB , JAVA byte [] DigestInputStream ( InputStream).

Thomas Pornin ( FileInputStream), :

mddigest   = java.security.MessageDigest.getInstance('MD5'); 

bufsize = 8192;

fid = fopen(filename);

while ~feof(fid)
    [currData,len] = fread(fid, bufsize, '*uint8');       
    if ~isempty(currData)
        mddigest.update(currData, 0, len);
    end
end

fclose(fid);

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

0.018s 713kB, 31 .

+2

All Articles