Text Encryption Unit

On viernes, 28 de enero de 2011 0 comentarios

Source Code

  1. unit unRC4;
  2. interface
  3. type
  4.   PByteArray = ^TByteArray;
  5.   TByteArray = Array [0..32767] Of Byte;
  6.   TRC4 = class
  7.   private
  8.     D               : array[Byte] of Byte;
  9.     I,J             : Byte;
  10.     procedure Init(const Key: string);
  11.     procedure Done;
  12.     procedure Code(Source, Dest: pChar; Count: Integer);
  13.   public
  14.     function Encrypt(S: pChar; const Password: string): AnsiString;
  15.     function Decrypt(S: pChar; const Password: string): AnsiString;
  16.   end;
  17. implementation
  18. { TRC4.Encrypt
  19.   This function will return the text(S) encrypted with the chosen password. }
  20. function TRC4.Encrypt(S: pChar; const Password: string): AnsiString;
  21. begin
  22.   SetLength(Result, Length(S));
  23.   Init(Password);
  24.   Code(pChar(S), pChar(Result), Length(S));
  25.   Done;
  26. end;
  27. { TRC4.Decrypt
  28.   This function will return the text(S) decrypted with the chosen password. }
  29. function TRC4.Decrypt(S: pChar; const Password: string): AnsiString;
  30. begin
  31.   SetLength(Result, Length(S));
  32.   Init(Password);
  33.   Code(pChar(S), pChar(Result), Length(S));
  34.   Done;
  35. end;
  36. { TRC4.Init
  37.   This routine will prepare the encryption/decryption. }
  38. procedure TRC4.Init(const Key: string);
  39. var
  40.   R, S, T, K        : Byte;
  41.   U,L               : Integer;
  42.   DummyArray        : array [0..1599] of Char;
  43. begin
  44. {$R-}
  45. {$Q-}
  46.   L := Length(Key);
  47.   I := 0;
  48.   J := 0;
  49.   R := 0;
  50.   U := 0;
  51.   for S := 0 to 255 do
  52.     D[S] := S;
  53.   for S := 0 to 255 do
  54.   begin
  55.     if (U < L) then
  56.       K := PByteArray(Key)[u]
  57.     else
  58.       K := 0;
  59.     Inc(U);
  60.     if (U >= L) then
  61.       U := 0;
  62.     Inc(R, D[S] + K);
  63.     T    := D[S];
  64.     D[S] := D[R];
  65.     D[R] := T;
  66.   end;
  67.   Code(@DummyArray, @DummyArray, 1600);
  68. end;
  69. { TRC4.Done
  70.   This routine will clean the variables used when encrypting/decrypting. }
  71. procedure TRC4.Done;
  72. begin
  73.   FillChar(D, sizeOf(D), 0);
  74.   FillChar(I, sizeOf(I), 0);
  75.   FillChar(J, sizeOf(J), 0);
  76. end;
  77. { TRC4.Code
  78.   This routine will encrypt the text. }
  79. procedure TRC4.Code(Source, Dest: pChar; Count: Integer);
  80. var
  81.   S                 : Integer;
  82.   T                 : Byte;
  83. begin
  84.   for S := 0 to (Count - 1) do
  85.   begin
  86.     Inc(I);
  87.     T := D[i];
  88.     Inc(J, T);
  89.     D[i] := D[J];
  90.     D[J] := T;
  91.     Inc(T, D[i]);
  92.     Byte(Dest[S]) := Byte(Source[S]) xor D[T];
  93.   end;
  94. end;
  95. end.

0 comentarios:

Publicar un comentario