HMAC-SHA256 in Delphi

Jacob picture Jacob · Jan 5, 2010 · Viewed 13.6k times · Source

I need to generate HMAC-SHA256 signatures for the Amazon web services API. The old DCPcrypt library has sha256 routines but does not do HMAC signing. Anyone know of a free hashing library I could use?

Answer

Remy Lebeau picture Remy Lebeau · Oct 21, 2016

Delphi ships with Indy installed, and Indy has a TIdHMACSHA256 class:

uses
  IdGlobal, IdHashSHA, IdHMAC, IdHMACSHA1, IdSSLOpenSSL;

function CalculateHMACSHA256(const value, salt: String): String;
var
  hmac: TIdHMACSHA256;
  hash: TIdBytes;
begin
  LoadOpenSSLLibrary;
  if not TIdHashSHA256.IsAvailable then
    raise Exception.Create('SHA256 hashing is not available!');
  hmac := TIdHMACSHA256.Create;
  try
    hmac.Key := IndyTextEncoding_UTF8.GetBytes(salt);
    hash := hmac.HashValue(IndyTextEncoding_UTF8.GetBytes(value));
    Result := ToHex(hash);
  finally
    hmac.Free;
  end;
end;