matlab hash算法

这里有个代码请问怎么输入可以得到结论,还是代码编写有问题
function h = hash(inp,meth)
% HASH - Convert an input variable into a message digest using any of
% several common hash algorithms
%
% USAGE: h = hash(inp,'meth')
%
% inp = input variable, of any of the following classes:
% char, uint8, logical, double, single, int8, uint8,
% int16, uint16, int32, uint32, int64, uint64
% h = hash digest output, in hexadecimal notation
% meth = hash algorithm, which is one of the following:
% MD2, MD5, SHA-1, SHA-256, SHA-384, or SHA-512
%
% NOTES: (1) If the input is a string or uint8 variable, it is hashed
% as usual for a byte stream. Other classes are converted into
% their byte-stream values. In other words, the hash of the
% following will be identical:
% 'abc'
% uint8('abc')
% char([97 98 99])
% The hash of the follwing will be different from the above,
% because class "double" uses eight byte elements:
% double('abc')
% [97 98 99]
% You can avoid this issue by making sure that your inputs
% are strings or uint8 arrays.
% (2) The name of the hash algorithm may be specified in lowercase
% and/or without the hyphen, if desired. For example,
% h=hash('my text to hash','sha256');
% (3) Carefully tested, but no warranty. Use at your own risk.
% (4) Michael Kleder, Nov 2005
%
% EXAMPLE:
%
% algs={'MD2','MD5','SHA-1','SHA-256','SHA-384','SHA-512'};
% for n=1:6
% h=hash('my sample text',algs{n});
% disp([algs{n} ' (' num2str(length(h)*4) ' bits):'])
% disp(h)
% end

inp=inp(:);
% convert strings and logicals into uint8 format
if ischar(inp) || islogical(inp)
inp=uint8(inp);
else % convert everything else into uint8 format without loss of data
inp=typecast(inp,'uint8');
end

% verify hash method, with some syntactical forgiveness:
meth=upper(meth);
switch meth
case 'SHA1'
meth='SHA-1';
case 'SHA256'
meth='SHA-256';
case 'SHA384'
meth='SHA-384';
case 'SHA512'
meth='SHA-512';
otherwise
end
algs={'MD2','MD5','SHA-1','SHA-256','SHA-384','SHA-512'};
if isempty(strmatch(meth,algs,'exact'))
error(['Hash algorithm must be ' ...
'MD2, MD5, SHA-1, SHA-256, SHA-384, or SHA-512']);
end

% create hash
x=java.security.MessageDigest.getInstance(meth);
x.update(inp);
h=typecast(x.digest,'uint8');
h=dec2hex(h)';
if(size(h,1))==1 % remote possibility: all hash bytes 128, so pad:
h=[repmat('0',[1 size(h,2)]);h];
end
h=lower(h(:)');
clear x
return

第1个回答  推荐于2016-07-19
代码没问题,可这样输入:
>> algs='MD2';h=hash('my sample text',algs)

h =

afe9e1be501aed6a3f90ec6c2ff8322e
>> algs='MD5';h=hash('abcd',algs)

h =

e2fc714c4727ee9395f324cd2e7f331f
>> algs='MD5';h=hash('1234',algs)

h =

81dc9bdb52d04dc20036dbd8313ed055
>> algs='SHA-1';h=hash('1234',algs)

h =

7110eda4d09e062aa5e4a390b0a572ac0d2c0220追问

请问是直接在代码底下输入algs='SHA-1';h=hash('1234',algs),然后运行就可以了?

追答

不是在代码底下输入,而是在matlab的命令行窗口中,如下截图

本回答被提问者和网友采纳
相似回答