SHA1.pas 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. unit SHA1;
  2. {
  3. SHA1.pas: System.Hash.pas wrapper in the style of the old version of this file:
  4. SHA1.pas: SHA-1 hash implementation, based on RFC 3174 and MD5.pas
  5. Author: Jordan Russell, 2010-02-24
  6. License for SHA1.pas: Public domain, no copyright claimed
  7. }
  8. interface
  9. uses
  10. System.Hash;
  11. type
  12. TSHA1Context = record
  13. hash: THashSHA1;
  14. end;
  15. TSHA1Digest = array[0..19] of Byte;
  16. procedure SHA1Init(var ctx: TSHA1Context);
  17. procedure SHA1Update(var ctx: TSHA1Context; const buffer; len: Cardinal);
  18. function SHA1Final(var ctx: TSHA1Context): TSHA1Digest;
  19. function SHA1Buf(const Buffer; Len: Cardinal): TSHA1Digest;
  20. function SHA1DigestsEqual(const A, B: TSHA1Digest): Boolean;
  21. function SHA1DigestToString(const D: TSHA1Digest): String;
  22. implementation
  23. procedure SHA1Init(var ctx: TSHA1Context);
  24. begin
  25. ctx.hash := THashSHA1.Create;
  26. end;
  27. procedure SHA1Update(var ctx: TSHA1Context; const buffer; len: Cardinal);
  28. begin
  29. ctx.hash.Update(buffer, len);
  30. end;
  31. function SHA1Final(var ctx: TSHA1Context): TSHA1Digest;
  32. begin
  33. var HashAsBytes := ctx.hash.HashAsBytes;
  34. Move(HashAsBytes[0], Result[0], SizeOf(Result));
  35. end;
  36. { New functions by JR: }
  37. function SHA1Buf(const Buffer; Len: Cardinal): TSHA1Digest;
  38. var
  39. Context: TSHA1Context;
  40. begin
  41. SHA1Init(Context);
  42. SHA1Update(Context, Buffer, Len);
  43. Result := SHA1Final(Context);
  44. end;
  45. function SHA1DigestsEqual(const A, B: TSHA1Digest): Boolean;
  46. var
  47. I: Integer;
  48. begin
  49. for I := Low(TSHA1Digest) to High(TSHA1Digest) do
  50. if A[I] <> B[I] then begin
  51. Result := False;
  52. Exit;
  53. end;
  54. Result := True;
  55. end;
  56. function SHA1DigestToString(const D: TSHA1Digest): String;
  57. const
  58. Digits: array[0..15] of Char = '0123456789abcdef';
  59. var
  60. Buf: array[0..39] of Char;
  61. P: PChar;
  62. I: Integer;
  63. begin
  64. P := @Buf[0];
  65. for I := 0 to 19 do begin
  66. P^ := Digits[D[I] shr 4];
  67. Inc(P);
  68. P^ := Digits[D[I] and 15];
  69. Inc(P);
  70. end;
  71. SetString(Result, Buf, 40);
  72. end;
  73. end.