comparison core/tools/hash.m @ 0:e9a9cd732c1e tip

first hg version after svn
author wolffd
date Tue, 10 Feb 2015 15:05:51 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:e9a9cd732c1e
1 function h = hash(inp,meth)
2 % HASH - Convert an input variable into a message digest using any of
3 % several common hash algorithms
4 %
5 % USAGE: h = hash(inp,'meth')
6 %
7 % inp = input variable, of any of the following classes:
8 % char, uint8, logical, double, single, int8, uint8,
9 % int16, uint16, int32, uint32, int64, uint64
10 % h = hash digest output, in hexadecimal notation
11 % meth = hash algorithm, which is one of the following:
12 % MD2, MD5, SHA-1, SHA-256, SHA-384, or SHA-512
13 %
14 % NOTES: (1) If the input is a string or uint8 variable, it is hashed
15 % as usual for a byte stream. Other classes are converted into
16 % their byte-stream values. In other words, the hash of the
17 % following will be identical:
18 % 'abc'
19 % uint8('abc')
20 % char([97 98 99])
21 % The hash of the follwing will be different from the above,
22 % because class "double" uses eight byte elements:
23 % double('abc')
24 % [97 98 99]
25 % You can avoid this issue by making sure that your inputs
26 % are strings or uint8 arrays.
27 % (2) The name of the hash algorithm may be specified in lowercase
28 % and/or without the hyphen, if desired. For example,
29 % h=hash('my text to hash','sha256');
30 % (3) Carefully tested, but no warranty. Use at your own risk.
31 % (4) Michael Kleder, Nov 2005
32 %
33 % EXAMPLE:
34 %
35 % algs={'MD2','MD5','SHA-1','SHA-256','SHA-384','SHA-512'};
36 % for n=1:6
37 % h=hash('my sample text',algs{n});
38 % disp([algs{n} ' (' num2str(length(h)*4) ' bits):'])
39 % disp(h)
40 % end
41
42 inp=inp(:);
43 % convert strings and logicals into uint8 format
44 if ischar(inp) || islogical(inp)
45 inp=uint8(inp);
46 else % convert everything else into uint8 format without loss of data
47 inp=typecast(inp,'uint8');
48 end
49
50 % verify hash method, with some syntactical forgiveness:
51 meth=upper(meth);
52 switch meth
53 case 'SHA1'
54 meth='SHA-1';
55 case 'SHA256'
56 meth='SHA-256';
57 case 'SHA384'
58 meth='SHA-384';
59 case 'SHA512'
60 meth='SHA-512';
61 otherwise
62 end
63 algs={'MD2','MD5','SHA-1','SHA-256','SHA-384','SHA-512'};
64 if isempty(strmatch(meth,algs,'exact'))
65 error(['Hash algorithm must be ' ...
66 'MD2, MD5, SHA-1, SHA-256, SHA-384, or SHA-512']);
67 end
68
69 % create hash
70 x=java.security.MessageDigest.getInstance(meth);
71 x.update(inp);
72 h=typecast(x.digest,'uint8');
73 h=dec2hex(h)';
74 if(size(h,1))==1 % remote possibility: all hash bytes < 128, so pad:
75 h=[repmat('0',[1 size(h,2)]);h];
76 end
77 h=lower(h(:)');
78 clear x
79 return