Could anyone help me matlab code for SHA-1,SHA-2 and SHA-3?
68 views (last 30 days)
Show older comments
Ei Ei Mon on 4 Jul 2018
Commented: Stephan Piotrowski on 8 Jan 2022
I would like to perform hashing using SHA-1,SHA-2 and SHA-3. Could anyone guide the link of Matlab code for hashing.
Bart McCoy on 13 Nov 2019
Edited: Bart McCoy on 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:
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);
hashStr(end+1:end+2) = hash_hex(k,:);
% Final answer is in 'hashStr'
Stephan Piotrowski on 8 Jan 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):
I was then able to proceed much the same way with
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.
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!