Encrypt/Decrypt files  

Send By: Radikal (Q3 Team)
Web : http://www.q3.nu
Email: radikal@q3.nu
Date: 06/06/20

Tip accessed 759 times

 


This tip is similar to the tip:

[550] - Encrypt/Decrypt JPGs

good... the funcion is just a little bit different...

This is a function than encrypt the content of a file, usind a pseudo-random password
The same funcion used over a encrypted file with the same password, restore the original file.

Here is the function and a call example, all placed in a OnClick event:


 procedure TForm1.Button2Click(Sender: TObject);

   procedure EncriptaFichero(Ori,Dest: string; Clave:integer);
   {
     Encripta el ficehro 'Ori', depositandolo en el fichero 'Dest'
     cusando como clave 'Clave'.
     Una pasada: encripta, otra pasada sobre el fichero encriptado, con la
     misma clave, lo desencripta.
     Ori: Nombre del fichero original (Source filename)
     Dest: Nombre del fichero encriptado (Destination filename) }

   const
     MAXBUFFER        = 4096;  //4k de buffer;
   var
     Buffer           : array[1..MAXBUFFER] of byte;
     Origen, Destino  : TFileStream;
     n, Leidos        : integer;
   begin
     Origen  :=TFileStream.Create(Ori,fmOpenRead+fmShareDenyWrite);
     Destino :=TFileStream.Create(Dest,fmCreate);
     RandSeed:=Clave;
     try
       repeat
         Leidos:=Origen.Read( Buffer[1],MAXBUFFER );
         for n:=1 to Leidos do begin
           Buffer[n]:=Buffer[n] xor Random(256);
         end;
         Destino.Write(Buffer[1],Leidos);
       until (Leidos < MAXBUFFER);
     finally
       Origen.Free;
       Destino.Free;
     end;
   end;

 begin
   {Ejemplo de llamada:}
   {Call example:}

   {Encriptar el fichero Test.txt con la clave 666:}
   {Encrypt the TEST.txt file with the pasword: 666}

   try
     EncriptaFichero('c:\kk\Test.txt','c:\kk\Test.dat',666);
   except
     on e:exception do begin
       ShowMessage( 'Error: No se pudo Desencriptar el fichero.'+#13+
                    'Motivo: '+e.Message);
     end;
   end;


   {Desencripta el fichero Test.dat con la clave 666:}
   {Decrypt the Test.dat file with the pasword: 666}
   try
     EncriptaFichero('c:\kk\Test.dat','c:\kk\Test.txt',666);
   except
     on e:exception do begin
       ShowMessage( 'Error: No se pudo encriptar el fichero.'+#13+
                    'Motivo: '+e.Message);
     end;
   end;

 end;