MATLAB: How to replicate “two hash iterations (denoted SHA256^2 ie “SHA256 function squared”)” in MATLAB

bitcoincryptohashsha-256

To demonstrate my understanding of the Bitcoin mining process, I have been trying to replicate it in MATLAB. However I am not able to get the same proper final hash. In the following example: Block Hashing Example
% code
clear all; close all;
header_hex = ['01000000',...
'81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000',...
'e320b6c2fffc8d750423db8b1eb942ae710e951ed797f7affc8892b0f1fc122b',...
'c7f5d74d',...
'f2b9441a',...
'42a14695'];
% Convert Hex to Bin
header_bin = dec2bin(hex2dec(header_hex));
% Initiate Java Digester
md = java.security.MessageDigest.getInstance('SHA-256');
% First Hash
pass1 = sprintf('%2.2x',typecast(md.digest(int8(header_bin)), 'uint8')');
% Convert to Binary
pass1_bin = dec2bin(hex2dec(pass1));
% Second Hash
pass2 = sprintf('%2.2x',typecast(md.digest(int8(pass1_bin)), 'uint8')');

Best Answer

dec2bin, hex2dec and co don't work the way you think they're doing.
>> hex2dec(header_hex)
ans =
1.78220342011972e+190
You get just one number. Not a decimal string. You would have to first reshape your hex header into rows of 2 characters (8 bits) for it to work. As for the conversions to binary, I don't understand what you're trying to do. They're not necessary.
Here's how to do it:
header_hex = ['01000000',...
'81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000',...
'e320b6c2fffc8d750423db8b1eb942ae710e951ed797f7affc8892b0f1fc122b',...
'c7f5d74d',...
'f2b9441a',...
'42a14695'];
% Convert Hex to numbers
header = hex2dec(reshape(header_hex, 2, [])');
% Initiate Java Digester
md = java.security.MessageDigest.getInstance('SHA-256');
% First Hash
pass1 = typecast(md.digest(header), 'uint8'); %matlab will automatically convert the input to int8
% Second Hash
pass2 = typecast(md.digest(pass1), 'uint8'); %certainly don't use int8(pass1) as that would convert all uint8>127 to 127. Use typecast, or let matlab do it.
% Display
sprintf('%02x', pass2) %your format string was also wrong