[fpc-pascal] HMAC_SHA1 and FPC

silvioprog silvioprog at gmail.com
Sat Mar 23 16:24:53 CET 2013


2013/3/23 Tony Whyman <tony.whyman at mccallumwhyman.com>

>  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.
>

Very nice. I will analyze this routine and see if I can remove the
dependence of DCP library. Thank you!

-- 
Silvio Clécio
My public projects - github.com/silvioprog
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20130323/098e506c/attachment.html>


More information about the fpc-pascal mailing list