Advertisement
Guest User

Untitled

a guest
Mar 24th, 2013
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 2.12 KB | None | 0 0
  1. (*
  2.   HMAC plugin.
  3.   Copyright (C) 2012-2014 Silvio Clecio.
  4.  
  5.   Please see the LICENSE file.
  6. *)
  7.  
  8. unit HMAC;
  9.  
  10. {$mode objfpc}{$H+}
  11.  
  12. interface
  13.  
  14. uses
  15.   SHA1;
  16.  
  17. const
  18.   HEX_TABLE: array[0..15] of Char = '0123456789abcdef';
  19.   SHA1_BLOCK_SIZE = 64;
  20.   SHA1_BLOCK_COUNT = 20;
  21.  
  22. function SHA1Raw(const ABuffer; const ABufferLength: PtrUInt): string;
  23. function HMACSHA1(const AKey, AMessage: string): string;
  24.  
  25. implementation
  26.  
  27. function SHA1Raw(const ABuffer; const ABufferLength: PtrUInt): string;
  28. var
  29.   I: Byte;
  30.   VDest: PChar;
  31.   VDigest: TSHA1Digest;
  32.   VContext: TSHA1Context;
  33. begin
  34.   SHA1Init(VContext);
  35.   SHA1Update(VContext, ABuffer, ABufferLength);
  36.   SHA1Final(VContext, VDigest);
  37.   SetLength(Result, SHA1_BLOCK_COUNT);
  38.   VDest := Pointer(Result);
  39.   for I := 0 to SHA1_BLOCK_COUNT - 1 do
  40.   begin
  41.     VDest^ := Char(VDigest[I]);
  42.     Inc(VDest);
  43.   end;
  44. end;
  45.  
  46. function HMACSHA1(const AKey, AMessage: string): string;
  47. var
  48.   I: Byte;
  49.   VDest: PChar;
  50.   VLenght: PtrUInt;
  51.   VDigest: TSHA1Digest;
  52.   VKey, VOPad, VIPad: string;
  53. begin
  54.   VLenght := Length(AKey);
  55.   if VLenght > SHA1_BLOCK_SIZE then
  56.   begin
  57.     SetLength(VKey, SHA1_BLOCK_SIZE);
  58.     FillChar(Pointer(VKey)^, SHA1_BLOCK_SIZE, #0);
  59.     VKey := SHA1Raw(Pointer(AKey)^, VLenght) + VKey;
  60.   end
  61.   else
  62.   begin
  63.     SetLength(VKey, SHA1_BLOCK_SIZE - VLenght);
  64.     FillChar(Pointer(VKey)^, SHA1_BLOCK_SIZE - VLenght, #0);
  65.     VKey := AKey + VKey;
  66.   end;
  67.   SetLength(VOPad, SHA1_BLOCK_SIZE);
  68.   FillChar(Pointer(VOPad)^, SHA1_BLOCK_SIZE, $5c);
  69.   SetLength(VIPad, SHA1_BLOCK_SIZE);
  70.   FillChar(Pointer(VIPad)^, SHA1_BLOCK_SIZE, $36);
  71.   for I := 1 to SHA1_BLOCK_SIZE do
  72.   begin
  73.     VOPad[I] := Char(Byte(VOPad[I]) xor Byte(VKey[I]));
  74.     VIPad[I] := Char(Byte(VIPad[I]) xor Byte(VKey[I]));
  75.   end;
  76.   VIPad := VIPad + AMessage;
  77.   VDigest := SHA1String(VOPad + SHA1Raw(Pointer(VIPad)^, Length(VIPad)));
  78.   SetLength(Result, SHA1_BLOCK_COUNT * 2);
  79.   VDest := Pointer(Result);
  80.   for I := 0 to SHA1_BLOCK_COUNT - 1 do
  81.   begin
  82.     VDest[0] := HEX_TABLE[(VDigest[I] shr 4) and 15];
  83.     VDest[1] := HEX_TABLE[VDigest[I] and 15];
  84.     Inc(VDest, 2);
  85.   end;
  86. end;
  87.  
  88. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement