Could anyone help me matlab code for SHA-1,SHA-2 and SHA-3?
40 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I would like to perform hashing using SHA-1,SHA-2 and SHA-3. Could anyone guide the link of Matlab code for hashing.
Risposte (1)
Bart McCoy
il 13 Nov 2019
Modificato: Bart McCoy
il 13 Nov 2019
MATLAB's internal .net classes support MD5, SHA1, SHA256, SHA384, and SHA512.
I don't think the new SHA3 is available in there yet. Implementation is easy.
I heard about this class from some website (lost the reference), but they didn't have any details.
I was able to guess my way through it without documentation.
% Example Code: Create an MD5 crypto-hash of an arbitrary string, "str"
% Main class of interest: System.Security.Cryptography.HashAlgorithm
% Example String to hash with MD5
str = 'hello there big world';
% Create any specified cryptographic hasher.
% Supported string args include 'MD5', 'SHA1', 'SHA256', 'SHA384', 'SHA512'.
% That's what I could figure out by random guessing... 'SHA3' didn't work.
hasher = System.Security.Cryptography.HashAlgorithm.Create('MD5');
% Convert the char string to uint8 type & run it through the hasher
% This is a Byte[] class object. Technically, this is the answer, but it needs reformatting
hash_byte = hasher.ComputeHash( uint8(str) );
% Convert the System.Byte class to MATLAB 1xN uint8 number array by typecasting. Lucky guess here
hash_uint8 = uint8( hash_byte );
% Convert uint8 to a Nx2 char array of HEX values
% Example Result:
% '12'
% '58'
% '2D'
% etc.
hash_hex = dec2hex(hash_uint8);
% FINALLY, convert the Nx2 hex char array to a 1x2N format
% Example Result: '12582D...'
hashStr = str([]);
nBytes = length(hash_hex);
for k=1:nBytes
hashStr(end+1:end+2) = hash_hex(k,:);
end
% Final answer is in 'hashStr'
'12582D12558894BE98DDD84E13B305EB'
5 Commenti
Walter Roberson
il 23 Ago 2021
Image_As_A_vector = reshape(typecast(YourImage, 'uint8'), 1, []));
Stephan Piotrowski
il 8 Gen 2022
Thanks for this example! I have no idea how to find more documentation about the way you define the hasher object. In my case, I wanted to hash numeric arrays rather than a string. For posterity, I'll leave some general learning here. You need to convert the numeric array into a 1D character array before passing it into hasher.ComputeHash. In my case, I chose this method (array_in is an n by 1 numeric array):
array_in=char(strjoin(string(reshape(array_in,1,[]))));
I was then able to proceed much the same way with
hash_byte=hasher.ComputeHash(uint8(array_in));
and so on. In principle, there might be some rare cases where unequal inputs result in the same hash if the conversion to a character array works out in an enexpected way. But it works for my purposes.
Vedere anche
Categorie
Scopri di più su Numeric Types in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!