[fpc-pascal] HMAC_SHA1 and FPC

Tony Whyman tony.whyman at mccallumwhyman.com
Sat Mar 23 11:34:20 CET 2013


Silvio,

I had the same requirement for an HMAC and used the DCP library:

http://wiki.freepascal.org/DCPcrypt

I then used the following code snippet to generate the HMAC

Regards

Tony Whyman
MWA

unit hmac;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils;

procedure MakeHMAC(text: string; var seed: LongInt; var hash: string);
function ValidateHMAC(text: string; seed: LongInt; hmac: string): boolean;

implementation

uses DCPsha1;

function GenerateHash(seed: longint; data: string):string;
var b1, b2, b3, b4: byte;
    q: integer;
    sha1: TDCP_sha1;
    buffer: PChar;
    memsize: integer;
    len: integer;
begin
  len := Length(data);
  b1 := seed mod 256;
  q := seed div 256;
  b2 := q mod 256;
  q := q div 256;
  b3 := q mod 256;
  b4 := q div 256;

  sha1 := TDCP_sha1.Create(nil);
  try
    sha1.Init;
    memsize := len + 4;
    buffer := SysGetMem(memsize);
    try
      Move(b1,buffer^,1);
      Move(b2,(buffer+1)^,1);
      Move(b3,(buffer+2)^,1);
      Move(b4,(buffer+3)^,1);
      Move(data[1],(buffer+4)^,len);
      SHA1.Update(buffer^,len+4);
      setlength(Result,20);
      SHA1.Final(Result[1]);
    finally
      SysFreeMem(buffer);
    end;
  finally
    sha1.free;
  end;
end;

procedure MakeHMAC(text: string; var seed: LongInt;
  var hash: string);
begin
       Randomize;
       seed := Round(Random(MaxLongInt));
       hash := GenerateHash(seed,text);
       hash := GenerateHash(seed,hash);
end;

function ValidateHMAC(text: string; seed: LongInt; hmac: string): boolean;
var hash1, hash2: string;
begin
  hash1 := GenerateHash(seed,text);
  hash2 := GenerateHash(seed,hash1);
  Result := CompareMem(@(hmac[1]),@(hash2[1]),20)
end;

end.

On 23/03/13 05:28, silvioprog wrote:
> Hello,
>
> How to get HMAC_SHA1 using native functions of FPC?
>
> HMAC_SHA1:
> http://en.wikipedia.org/wiki/Hash-based_message_authentication_code#Examples_of_HMAC_.28MD5.2C_SHA1.2C_SHA256.29
>
> Thank you!
>
> -- 
> Silvio Clécio
> My public projects - github.com/silvioprog <http://github.com/silvioprog>
>
>
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-pascal

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20130323/6b0c6ff4/attachment.html>


More information about the fpc-pascal mailing list