Skip to content

THashSHA2.GetHMACAsBytes return the wrong value

class function THashSHA2.GetHMACAsBytes(const aData, aKey: TBytes; aHashVersion: TSHA2Version): TBytes;

var
  Count: UInt32;
  KeySize,DataSize,BufSize : Integer;
  aDigest,KeyBuffer, PadBuffer: TBytes;
  SHA2,SHA2_ : THashSHA2;

begin
  Result:=[];
  KeySize:=Length(akey);
  DataSize:=Length(aData);
  if aKey = nil then
    Exit;
  if aData = nil then
    Exit;
  SHA2:=THashSHA2.Create(aHashversion);
  BufSize:=SHA2.GetBlockSize;
  SetLength(KeyBuffer,BufSize);
  SetLength(PadBuffer,BufSize);
  if KeySize>BufSize then
  begin
    SHA2.Update(aKey);
    aDigest:=SHA2.GetDigest;
    System.Move(aDigest[0],KeyBuffer[0],SHA2.GetHashSize);
  end else
    System.Move(aKey[0], KeyBuffer[0], KeySize);
  // XOR the key buffer with the iPad value
  for Count := 0 to BufSize do
    PadBuffer[Count] := KeyBuffer[Count] xor $36;
  SHA2.Reset;
  SHA2.Update(PadBuffer);
  SHA2.Update(aData);
  aDigest:=SHA2.GetDigest;
  // XOR the key buffer with the oPad value
  for Count := 0 to 63 do
    PadBuffer[Count] := KeyBuffer[Count] xor $5C;
  // SHA256 the key buffer and the result of the inner SHA256 (Outer)
  SHA2.Reset;
  SHA2.Update(PadBuffer);
  SHA2.Update(aDigest);
  Result:=SHA2_.GetDigest;
end;

SHA2_ is not used in the main procedure but used to return the digest, it should be Result:=SHA2.GetDigest;

To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information