Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (*
- HMAC plugin.
- Copyright (C) 2012-2014 Silvio Clecio.
- Please see the LICENSE file.
- *)
- unit HMAC;
- {$mode objfpc}{$H+}
- interface
- uses
- SysUtils, SHA1;
- const
- SHA1_BLOCK_SIZE = 64;
- SHA1_BLOCK_COUNT = 20;
- SHA1_HEX_TABLE: array[0..15] of Char = '0123456789abcdef';
- function SHA1Raw(const ABuffer; const ABufferLength: PtrUInt): string;
- { TODO: function HMACMD5(const AKey, AMessage: string): string; }
- function HMACSHA1(const AKey, AMessage: string): string;
- implementation
- function SHA1Raw(const ABuffer; const ABufferLength: PtrUInt): string;
- var
- I: Byte;
- VBytes : TBytes;
- VDigest: TSHA1Digest;
- VContext: TSHA1Context;
- begin
- Result := '';
- SHA1Init(VContext);
- SHA1Update(VContext, ABuffer, ABufferLength);
- SHA1Final(VContext, VDigest);
- SetLength(VBytes, SHA1_BLOCK_COUNT);
- Move(VDigest, VBytes[0], SHA1_BLOCK_COUNT);
- for I := 0 to SHA1_BLOCK_COUNT - 1 do
- Result := Result + Char(VBytes[I]);
- end;
- function HMACSHA1(const AKey, AMessage: string): string;
- var
- I: Byte;
- VDest: PChar;
- VLenght: PtrUInt;
- VDigest: TSHA1Digest;
- VKey, VOPad, VIPad: string;
- begin
- VLenght := Length(AKey);
- if VLenght > SHA1_BLOCK_SIZE then
- begin
- SetLength(VKey, SHA1_BLOCK_SIZE);
- FillChar(Pointer(VKey)^, SHA1_BLOCK_SIZE, #0);
- VKey := SHA1Raw(Pointer(AKey)^, VLenght) + VKey;
- end
- else
- begin
- SetLength(VKey, SHA1_BLOCK_SIZE - VLenght);
- FillChar(Pointer(VKey)^, SHA1_BLOCK_SIZE - VLenght, #0);
- VKey := AKey + VKey;
- end;
- SetLength(VOPad, SHA1_BLOCK_SIZE);
- FillChar(Pointer(VOPad)^, SHA1_BLOCK_SIZE, $5c);
- SetLength(VIPad, SHA1_BLOCK_SIZE);
- FillChar(Pointer(VIPad)^, SHA1_BLOCK_SIZE, $36);
- for I := 1 to SHA1_BLOCK_SIZE do
- begin
- VOPad[I] := Char(Byte(VOPad[I]) xor Byte(VKey[I]));
- VIPad[I] := Char(Byte(VIPad[I]) xor Byte(VKey[I]));
- end;
- VIPad := VIPad + AMessage;
- VDigest := SHA1String(VOPad + SHA1Raw(Pointer(VIPad)^, Length(VIPad)));
- SetLength(Result, SHA1_BLOCK_COUNT * 2);
- VDest := Pointer(Result);
- for I := 0 to SHA1_BLOCK_COUNT - 1 do
- begin
- VDest[0] := SHA1_HEX_TABLE[(VDigest[I] shr 4) and 15];
- VDest[1] := SHA1_HEX_TABLE[VDigest[I] and 15];
- Inc(VDest, 2);
- end;
- end;
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement