尝试实施 SHA-1

Trying to implement SHA-1

我正在尝试实现 SHA-1 代码,但是当我尝试计算 32 位长度的 80 个字时,我得到了一些奇怪的输出,这是伪代码。

 message='Hello';
 message=dec2bin(message,8);
  message=reshape(message,1,40);  
message(end:end+1)=0;
a=repmat('0', 1, 409);
message=strcat(message,a);
lengthh=length(dec2bin(40,8));
a=repmat('0', 1, 64-lengthh);
b=dec2bin(40,8);
 message=strcat(message,a,b);
k=1;
s='';
M=repmat(s,16,32);
W= repmat(s,80,32);
for i=1:32:512
M(k,:)=message(i:i+31);
 k=k+1;
end
Hash(1,:)  =dec2bin(hex2dec('67452301'),32);
Hash(2,:) = dec2bin(hex2dec('efcdab89'),32);
Hash(3,:) = dec2bin(hex2dec('98badcfe'),32);
Hash(4,:) = dec2bin(hex2dec('10325476'),32);
Hash(5,:) =dec2bin(hex2dec('c3d2e1f0'),32);

W(1:16,:)=M(1:16,:);
for i=17:80
 W(i,:)=  bitxor(uint32(W(i-3,:)),uint32(W(i-8,:)),'uint32');
 end

输出为

val =

   00000111110111100000101110111100
   00101000000000000000000000000000
   00000000000000000000000000000000
   00000000000000000000000000000000
   00000000000000000000000000000000
    00000000000000000000000000000000
   00000000000000000000000000000000
  00000000000000000000000000000000
  00000000000000000000000000000000
    00000000000000000000000000000000
  00000000000000000000000000000000
   00000000000000000000000000000000
  00000000000000000000000000000000
  00000000000000000000000000000000
    00000000000000000000000000000000
   00000000000000000000000000101000



         00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000101000


00000000000000000000000000101000



00000000000000000000000000000000
00000000000000000000000000101000

00000000000000000000000000101000


00000000000000000000000000101000

00000000000000000000000000101000





00000000000000000000000000101000

00000000000000000000000000000000
00000000000000000000000000101000

00000000000000000000000000000000
00000000000000000000000000101000


00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000101000


00000000000000000000000000101000

00000000000000000000000000101000

00000000000000000000000000101000


00000000000000000000000000000000
00000000000000000000000000101000


00000000000000000000000000000000
00000000000000000000000000101000

00000000000000000000000000101000

00000000000000000000000000000000
00000000000000000000000000101000




00000000000000000000000000101000

问题从第 17 行开始,开始出现一些奇怪的符号,谁能帮忙。

我建议您避免自己实现哈希算法;这可能很痛苦,尤其是在 Matlab 中。请改用内置的 Java 哈希框架,它快如闪电且防弹:

% Your message to be hashed...
message = 'Hello';

% Convert the message into a byte array...
message_bytes = getByteStreamFromArray(double(message));

% Create an instance of a Java MessageDigest with the desired algorithm:
md = java.security.MessageDigest.getInstance('SHA-1');
md.update(message_bytes);

% Properly format the computed hash as an hexadecimal string:
hash = reshape(dec2hex(typecast(md.digest(),'uint8'))',1,[]);

输出将是 F7FF9E8B7BB2E09B70935A5D785E0CC5D9D0ABF0。例如,您可以使用 this online application 验证结果的正确性。