| 1 |
function hash = calculateMD5Hash(filename) |
| 2 |
% CALCULATEMD5HASH calculate a MD5 hash of a file |
| 3 |
% |
| 4 |
% This functionality is built-in into Octave but uses Java in MATLAB. |
| 5 |
|
| 6 |
switch getEnvironment |
| 7 |
case 'Octave' |
| 8 |
hash = md5sum(filename); |
| 9 |
|
| 10 |
case 'MATLAB' |
| 11 |
% There are some MD5 implementations in MATLAB, but those |
| 12 |
% tend to be slow and licensing is unclear. |
| 13 |
% Rolling our own implementation is unwanted, especially since this |
| 14 |
% is a cryptographic hash, even though its security has been |
| 15 |
% broken. Instead we make use of the Java libraries. |
| 16 |
% Unless the "-nojvm" flag is specified, this should work well. |
| 17 |
|
| 18 |
MD5 = java.security.MessageDigest.getInstance('MD5'); |
| 19 |
|
| 20 |
% Open the file |
| 21 |
fid = fopen(filename, 'r'); |
| 22 |
|
| 23 |
% Make sure fid is closed |
| 24 |
finally_close = onCleanup(@()fclose(fid)); |
| 25 |
|
| 26 |
% Faster file digest based on code by Jan Simon as in |
| 27 |
% http://www.mathworks.com/matlabcentral/fileexchange/31272-datahash |
| 28 |
data = fread(fid, '*uint8'); |
| 29 |
MD5.update(data); |
| 30 |
|
| 31 |
hash = reshape(dec2hex(typecast(MD5.digest(),'uint8')).', 1, 32); |
| 32 |
end |
| 33 |
|
| 34 |
hash = lower(hash); |
| 35 |
end |