MatrixBerryCore
hash.m
Go to the documentation of this file.
1 function hashVec=hash(inpArr,methodName)
2 if nargin<2
3  methodName='SHA-1';
4 end
5 switch (class(inpArr))
6  case 'struct'
7  hashVec=structhash(inpArr,methodName);
8  case 'cell'
9  hashVec=cellhash(inpArr,methodName);
10  otherwise
11  if ~isempty(inpArr)
12  hashVec=hashinner(inpArr,methodName);
13  else
14  hashVec=hashinner('valueisemptynohash',methodName);
15  end
16 end
17 end
18 %
19 function hashVec=structhash(structB,methodName)
20 fieldNames=fieldnames(structB);
21 hashMat=mxberry.core.hash(...
22  [{'itisastruct';num2str(size(structB))};fieldNames],methodName);
23 %
24 hashMat=[hashMat;cellhash(struct2cell(structB),methodName)];
25 hashVec=mxberry.core.hash(hashMat,methodName);
26 end
27 %
28 function hashVec=cellhash(cellB,methodName)
29 import mxberry.core.hash;
30 %
31 hashCell=cellfun(@(x)hash(x,methodName),cellB,'UniformOutput',false);
32 hashCell=reshape(hashCell,[],1);
33 hashMat=cell2mat(hashCell);
34 hashMat=[hash(['itisacell' num2str(size(cellB))]);hashMat];
35 hashVec=hash(hashMat,methodName);
36 end
37 
38 function h = hashinner(inpArr,meth)
39 
40 inpVec=inpArr(:);
41 % convert strings and logicals into uint8 format
42 if ischar(inpVec) || islogical(inpVec)
43  byteVec=uint8(inpVec);
44 else % convert everything else into uint8 format without loss of data
45  if isnumeric(inpVec)&&isreal(inpVec)
46  byteVec=typecast(inpVec,'uint8');
47  else
48  byteVec=getByteStreamFromArray(inpArr);
49  end
50 end
51 
52 % verify hash method, with some syntactical forgiveness:
53 meth=upper(meth);
54 switch meth
55  case 'SHA1'
56  meth='SHA-1';
57  case 'SHA256'
58  meth='SHA-256';
59  case 'SHA384'
60  meth='SHA-384';
61  case 'SHA512'
62  meth='SHA-512';
63  otherwise
64 end
65 algs={'MD2','MD5','SHA-1','SHA-256','SHA-384','SHA-512'};
66 if isempty(strcmp(meth,algs))
67  mxberry.core.throwerror('wrongInput',['Hash algorithm must be ' ...
68  'MD2, MD5, SHA-1, SHA-256, SHA-384, or SHA-512']);
69 end
70 % create hash
71 x=java.security.MessageDigest.getInstance(meth);
72 x.update(byteVec);
73 h=typecast(x.digest,'uint8');
74 h=dec2hex(h)';
75 if(size(h,1))==1 % remote possibility: all hash bytes < 128, so pad:
76  h=[repmat('0',[1 size(h,2)]);h];
77 end
78 h=lower(h(:)');
79 clear x
80 end
function cellhash(in cellB, in methodName)
function hash(in inpArr, in methodName)
OBJECTHASH counts the hash of input object/array.
function hashinner(in inpArr, in meth)
HASH - Convert an input variable into a message digest using any of several common hash algorithms...
function structhash(in structB, in methodName)
function cell2mat(in inpCArr)
CELL2MAT does the same as the built-in cell2mat function but a) 20% faster b) works with cell arrays ...