分享:用四十种语言分别写一个MD5算法 之20 MATLAB语言MD5算法
function digest = md5(message)
%% Helper Function Definitions
%This function converts a binary representation of a number or vector
%of numbers from a string to a row vector of 1's and 0's
function matrix = binStr2mat(binStr)
matrix = zeros(size(binStr));
for n = (1:numel(binStr))
matrix(n) = str2double(binStr(n));
end
end
%This acts as a "lower <= x <= upper" operator
function trueFalse = inRange(lowerBound,theValue,upperBound)
trueFalse = (lowerBound <= theValue) && (theValue <= upperBound);
end
%This converts a decimal number into its 32-bit binary representation,
%and I'm pretty sure it is little-endian
function binaryRep = to32BitBin(decimal)
binaryRep = binStr2mat(dec2bin(decimal,32));
end
%This converts a decimal number into its 64-bit binary representation,
%and I'm pretty sure it is little-endian
function binaryRep = to64BitBin(decimal)
binaryRep = binStr2mat(dec2bin(decimal,64));
end
%This adds multiple binary numbers together modulo 2^32. The sum of these
%numbers will rap around if the sum of two numbers is >= 2^32
function result = addBinary(varargin)
result = 0;
for l = (1:numel(varargin))
temp = num2str(varargin{l});
temp(temp == ' ') = [];
result = mod(result + bin2dec(temp),2^32);
end
result = to32BitBin(result);
end
%% MD5 Hash Algorithm
%Define constants
%r is the bit-shift amount for each round
r =[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,...
&
function digest = md5(message)
%% Helper Function Definitions
%This function converts a binary representation of a number or vector
%of numbers from a string to a row vector of 1's and 0's
function matrix = binStr2mat(binStr)
matrix = zeros(size(binStr));
for n = (1:numel(binStr))
matrix(n) = str2double(binStr(n));
end
end
%This acts as a "lower <= x <= upper" operator
function trueFalse = inRange(lowerBound,theValue,upperBound)
trueFalse = (lowerBound <= theValue) && (theValue <= upperBound);
end
%This converts a decimal number into its 32-bit binary representation,
%and I'm pretty sure it is little-endian
function binaryRep = to32BitBin(decimal)
binaryRep = binStr2mat(dec2bin(decimal,32));
end
%This converts a decimal number into its 64-bit binary representation,
%and I'm pretty sure it is little-endian
function binaryRep = to64BitBin(decimal)
binaryRep = binStr2mat(dec2bin(decimal,64));
end
%This adds multiple binary numbers together modulo 2^32. The sum of these
%numbers will rap around if the sum of two numbers is >= 2^32
function result = addBinary(varargin)
result = 0;
for l = (1:numel(varargin))
temp = num2str(varargin{l});
temp(temp == ' ') = [];
result = mod(result + bin2dec(temp),2^32);
end
result = to32BitBin(result);
end
%% MD5 Hash Algorithm
%Define constants
%r is the bit-shift amount for each round
r =[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,...
&