Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > Varios
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 15-08-2005
Mick Mick is offline
Miembro
 
Registrado: may 2003
Posts: 405
Poder: 22
Mick Va por buen camino
Sigo insistiendo en que utilices el siguiente paquete:

http://www.cityinthesky.co.uk/files/dcpcrypt2.zip

No tienes ni porque instalar los componentes, basta con con descomprimas el zip y simplemente cojas la unit:

DCPbase64.pas

Esa unit solo tiene dos funciones para codificar y descodificar en base 64:

Código:
unit DCPbase64;

interface
uses
  Sysutils;

function Base64EncodeStr(const Value: string): string;
  { Encode a string into Base64 format }
function Base64DecodeStr(const Value: string): string;
  { Decode a Base64 format string }

....
Saludos
Responder Con Cita
  #2  
Antiguo 15-08-2005
Avatar de DarkByte
DarkByte DarkByte is offline
Miembro
 
Registrado: sep 2003
Ubicación: Desconocido
Posts: 1.322
Poder: 22
DarkByte Va por buen camino
Aja, probare con las units, muchas gracias Mick, te cuento que tal me va
__________________
:)
Responder Con Cita
  #3  
Antiguo 15-08-2005
Avatar de DarkByte
DarkByte DarkByte is offline
Miembro
 
Registrado: sep 2003
Ubicación: Desconocido
Posts: 1.322
Poder: 22
DarkByte Va por buen camino
Funciona a la perfección. Gracias Mick, ahí tienes tus 10 puntos
__________________
:)

Última edición por DarkByte fecha: 15-08-2005 a las 20:23:50. Razón: habia escrito "putos" en lugar de "puntos"
Responder Con Cita
  #4  
Antiguo 23-08-2005
Avatar de Al González
[Al González] Al González is offline
In .pas since 1991
 
Registrado: may 2003
Posts: 5.604
Poder: 30
Al González Es un diamante en brutoAl González Es un diamante en brutoAl González Es un diamante en brutoAl González Es un diamante en bruto
Smile Lo que buscaba

¡Hola a todos!

Cita:
Empezado por Mick
...Sigo insistiendo en que utilices el siguiente paquete:
http://www.cityinthesky.co.uk/files/dcpcrypt2.zip...DCPbase64.pas Esa unit solo tiene dos funciones para codificar y descodificar en base 64...
Cita:
Empezado por David Barton (el autor de la biblioteca)
...DCPcrypt is open source software...
También yo buscaba algo así para decodificar unos campos de texto que fueron codificados en PHP con la función base64_encode.

Gracias.

Un abrazo encriptado.

Al González.
Responder Con Cita
  #5  
Antiguo 20-09-2005
Avatar de Maury Manosalva
Maury Manosalva Maury Manosalva is offline
Miembro
 
Registrado: ago 2005
Posts: 101
Poder: 19
Maury Manosalva Va por buen camino
Unhappy No entiendo como funciona la Encriptacion.. Ayuda

Por favor entendidos en el tema, me pueden hacer el favor y de explicarme como trabajar con este programa para encriptar y desencriptar un archivo.. Nevcesito encriptar un txt y desencriptarlo para un manejo de treeview.. gracias mil.

Maury Manosalva
Responder Con Cita
  #6  
Antiguo 05-11-2005
Luis Castillo Luis Castillo is offline
Miembro
 
Registrado: jun 2003
Ubicación: Colombia
Posts: 102
Poder: 22
Luis Castillo Va por buen camino
De acuerdo

Estoy de acuerdo con el señor Maury. Seria posible que presentaran un vinculo donde narrara un poco sobre las bases de la encriptacion. Veo que hablan de formatos y demas reglas....

Quisiera iniciarme mas en este tema....

Les agradezco mucho


Gracias..
__________________
LK
Responder Con Cita
  #7  
Antiguo 05-11-2005
Avatar de Delphius
[Delphius] Delphius is offline
Miembro Premium
 
Registrado: jul 2004
Ubicación: Salta, Argentina
Posts: 5.582
Poder: 25
Delphius Va camino a la fama
puede ser:

Luis Castillo, aquí en los foros se ha tratado muchas veces este tema... ,es más... me acuerdo que he participado en algunos de ellos). Una simple búsqueda en los foros te resultará de utilidad:
http://www.clubdelphi.com/foros/sear...earchid=356387
http://www.clubdelphi.com/foros/sear...earchid=355898

De todas maneras, se puede saber un poco más si buscas en google:
http://www.google.com.ar/search?hl=e...%BAsqueda&meta=

Lo poco que aprendí de esto lo hice buscando, y buscando....
__________________
Delphius
[Guia de estilo][Buscar]
Responder Con Cita
  #8  
Antiguo 05-11-2005
Avatar de carlocf
carlocf carlocf is offline
Miembro
 
Registrado: oct 2005
Posts: 35
Poder: 0
carlocf Va por buen camino
Saludos a todo el foro

Para aquellos que les interesa la criptologia pueden visitar la pagina www.kriptopolis.com

Saludos
Carlo

Última edición por carlocf fecha: 05-11-2005 a las 15:29:05. Razón: Puse puden en vez de pueden
Responder Con Cita
  #9  
Antiguo 29-09-2014
principiodual principiodual is offline
Miembro
NULL
 
Registrado: ago 2014
Posts: 26
Poder: 0
principiodual Va por buen camino
Cita:
Empezado por Mick Ver Mensaje
Sigo insistiendo en que utilices el siguiente paquete:

http://www.cityinthesky.co.uk/files/dcpcrypt2.zip

No tienes ni porque instalar los componentes, basta con con descomprimas el zip y simplemente cojas la unit:

DCPbase64.pas

Esa unit solo tiene dos funciones para codificar y descodificar en base 64:

Código:
unit DCPbase64;

interface
uses
  Sysutils;

function Base64EncodeStr(const Value: string): string;
  { Encode a string into Base64 format }
function Base64DecodeStr(const Value: string): string;
  { Decode a Base64 format string }

....
Saludos
Buenas amigos, me gustaría hacer uso de ese paquete que habla, pero al dar link me dice que está caído, podría de alguna manera acceder a esa Unit para hacer las pruebas, es que he probado varios metodos de cifrados pero generan caracteres extraños y estoy trabajando con una base de datos de IBM en db2 y todos los caracteres extraños los convierte a cuadritos, por eso me gustaría probar un método que solo cifre con caracteres ascii o alfanúmericos. Si me puede orientar muchas gracias, de todas maneras sigo investigando. Saludos.
Responder Con Cita
  #10  
Antiguo 29-09-2014
Avatar de nlsgarcia
[nlsgarcia] nlsgarcia is offline
Miembro Premium
 
Registrado: feb 2007
Ubicación: Caracas, Venezuela
Posts: 2.206
Poder: 21
nlsgarcia Tiene un aura espectacularnlsgarcia Tiene un aura espectacular
principiodual

Cita:
Empezado por principiodual
...me gustaría probar un método que solo cifre con caracteres ASCII o Alfanuméricos...


Revisa esta información
Espero sea útil

Nelson.
Responder Con Cita
  #11  
Antiguo 29-09-2014
principiodual principiodual is offline
Miembro
NULL
 
Registrado: ago 2014
Posts: 26
Poder: 0
principiodual Va por buen camino
Cita:
Empezado por nlsgarcia Ver Mensaje
principiodual




Revisa esta información
Espero sea útil

Nelson.
Muchas gracias amigo, a chequear entonces , saludos.
Responder Con Cita
  #12  
Antiguo 29-09-2014
Avatar de pacopenin
pacopenin pacopenin is offline
Miembro
 
Registrado: sep 2010
Ubicación: Asturias
Posts: 382
Poder: 14
pacopenin Va por buen camino
Cita:
Empezado por principiodual Ver Mensaje
Buenas amigos, me gustaría hacer uso de ese paquete que habla, pero al dar link me dice que está caído, podría de alguna manera acceder a esa Unit para hacer las pruebas, es que he probado varios metodos de cifrados pero generan caracteres extraños y estoy trabajando con una base de datos de IBM en db2 y todos los caracteres extraños los convierte a cuadritos, por eso me gustaría probar un método que solo cifre con caracteres ascii o alfanúmericos. Si me puede orientar muchas gracias, de todas maneras sigo investigando. Saludos.
Buenas. El paquete al que te refieres es éste : http://www.cityinthesky.co.uk/opensource/dcpcrypt/

Saludos.
__________________
http://www.gestionportable.com
Responder Con Cita
  #13  
Antiguo 29-09-2014
principiodual principiodual is offline
Miembro
NULL
 
Registrado: ago 2014
Posts: 26
Poder: 0
principiodual Va por buen camino
Cita:
Empezado por pacopenin Ver Mensaje
Buenas. El paquete al que te refieres es éste : http://www.cityinthesky.co.uk/opensource/dcpcrypt/

Saludos.
Muchas gracias amigo, a revisar entonces.
Responder Con Cita
  #14  
Antiguo 01-10-2014
Avatar de nlsgarcia
[nlsgarcia] nlsgarcia is offline
Miembro Premium
 
Registrado: feb 2007
Ubicación: Caracas, Venezuela
Posts: 2.206
Poder: 21
nlsgarcia Tiene un aura espectacularnlsgarcia Tiene un aura espectacular
principiodual

Cita:
Empezado por principiodual
...me gustaría probar un método que solo cifre con caracteres ASCII o Alfanuméricos...


Revisa este código:
Código Delphi [-]
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Memo1: TMemo;
    Memo2: TMemo;
    Memo3: TMemo;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  TState = Array[0..3,0..3] of Byte;

var
  Form1: TForm1;

implementation

{$R *.dfm}

// Realiza operaciones matriciales de intercambio de filas
procedure ShiftRows(var State: TState);
var
   i,j,k : Integer;
begin
   for j := 1 to 3 do
   begin
      k := State[0,j];
      State[0,j] := State[1,j];
      State[1,j] := State[2,j];
      State[2,j] := State[3,j];
      State[3,j] := k;
   end;
end;

// Realiza operaciones matriciales de intercambio de columnas
procedure ShiftCols(var State: TState);
var
   i,j,k : Integer;
begin
   for j := 1 to 3 do
   begin
      k := State[j,0];
      State[j,0] := State[j,1];
      State[j,1] := State[j,2];
      State[j,2] := State[j,3];
      State[j,3] := k;
   end;
end;

// Realiza operaciones matriciales inversas de intercambio de filas
procedure InvShiftRows(var State: TState);
var
   i,j,k : Integer;
begin
   for j := 1 to 3 do
   begin
      k := State[3,j];
      State[3,j] := State[2,j];
      State[2,j] := State[1,j];
      State[1,j] := State[0,j];
      State[0,j] := k;
   end;
end;

// Realiza operaciones matriciales inversas de intercambio de columnas
procedure InvShiftCols(var State: TState);
var
   i,j,k : Integer;
begin
   for j := 1 to 3 do
   begin
      k := State[j,3];
      State[j,3] := State[j,2];
      State[j,2] := State[j,1];
      State[j,1] := State[j,0];
      State[j,0] := k;
   end;
end;

// Convierte una cadena de carácteres ASCII a su equivalente Hexadecimal
function StringToHex(S : String): String;
var
   i: Integer;
begin
   for i := 1 to Length(S) do
      Result := Result + IntToHex(Ord(S[i]), 2);
end;

// Convierte una cadena de carácteres Hexadecimal a su equivalente ASCII
function HexToString(S : String): String;
var
   i : Integer;
begin
   for i := 1 to Length(S) do
      if ((i mod 2) = 1) then
         Result := Result + Chr(StrToInt('0x' + Copy(S, i, 2)));
end;

// Cifra un String por medio de una clave con operaciones matriciales y funciones lógicas
function Encode(DataStr, Key : String) : String;
var
   i : Integer;
   AuxStr : String;
   AuxKey : LongWord;
   Src, Dst : TStringStream;
   State : TState;

begin

   Src := TStringStream.Create(DataStr);
   Dst := TStringStream.Create('');

   FillChar(State,Sizeof(State),#0);

   while Src.Read(State,Sizeof(State)) > 0 do
   begin
      ShiftRows(State);
      ShiftCols(State);
      Dst.WriteBuffer(State,Sizeof(State));
      FillChar(State,Sizeof(State),#0);
   end;

   AuxKey := 0;

   for i := 1 to length(Key) do
      AuxKey := (AuxKey + ord(Key[i])) xor Length(Key);

   for i:=1 to length(Dst.DataString) do
      AuxStr := AuxStr + chr(ord(Dst.DataString[i]) xor AuxKey);

   Result := StringToHex(AuxStr);

end;

// Descifra un String por medio de una clave con operaciones matriciales y funciones lógicas
function Decode(DataStr, Key : String) : String;
var
   i : Integer;
   AuxStr : String;
   AuxKey : LongWord;
   Src, Dst : TStringStream;
   State : TState;

begin

   DataStr := HexToString(DataStr);

   Src := TStringStream.Create(DataStr);
   Dst := TStringStream.Create('');

   FillChar(State,Sizeof(State),#0);

   while Src.Read(State,Sizeof(State)) > 0 do
   begin
      InvShiftCols(State);
      InvShiftRows(State);
      Dst.WriteBuffer(State,Sizeof(State));
      FillChar(State,Sizeof(State),#0);
   end;

   AuxKey := 0;

   for i := 1 to length(Key) do
      AuxKey := (AuxKey + ord(Key[i])) xor Length(Key);

   for i:=1 to length(Dst.DataString) do
      AuxStr := AuxStr + chr(ord(Dst.DataString[i]) xor AuxKey);

   Result := AuxStr;

end;

// Llama la función que Cifra una cadena de carácteres
procedure TForm1.Button1Click(Sender: TObject);
begin
   Memo2.Text := Encode(Memo1.Text, Edit1.Text);
end;

// Llama la función que Descifra una cadena de carácteres
procedure TForm1.Button2Click(Sender: TObject);
begin
   Memo3.Text := Decode(Memo2.Text, Edit1.Text);
end;

// Reset los controles del formulario
procedure TForm1.Button3Click(Sender: TObject);
begin
   Edit1.Text := EmptyStr;
   Memo1.Clear;
   Memo2.Clear;
   Memo3.Clear;
end;

end.
El código anterior en Delphi 7 sobre Windows 7 Professional x32, Cifra y Descifra una cadena de caracteres por medio de una clave utilizando operaciones matriciales y funciones lógicas, según se muestra en la siguiente imagen:



Nota: El código propuesto es útil como una opción de cifrado/descifrado de Strings, sin embargo si los requerimientos de la aplicación lo ameritan, te sugiero implementar el algoritmo Advanced Encryption Standard (AES) (Msg #16), el cual a sido adoptado como : El estándar de cifrado por el gobierno de los Estados Unidos.

Espero sea útil

Nelson.

Última edición por nlsgarcia fecha: 01-10-2014 a las 08:06:16.
Responder Con Cita
  #15  
Antiguo 01-10-2014
Avatar de Ñuño Martínez
Ñuño Martínez Ñuño Martínez is offline
Moderador
 
Registrado: jul 2006
Ubicación: Ciudad Catedral, Españistán
Posts: 6.000
Poder: 25
Ñuño Martínez Tiene un aura espectacularÑuño Martínez Tiene un aura espectacular
Cita:
Empezado por nlsgarcia Ver Mensaje
principiodual




Revisa este código:
Código Delphi [-]
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Memo1: TMemo;
    Memo2: TMemo;
    Memo3: TMemo;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  TState = Array[0..3,0..3] of Byte;

var
  Form1: TForm1;

implementation

{$R *.dfm}

// Realiza operaciones matriciales de intercambio de filas
procedure ShiftRows(var State: TState);
var
   i,j,k : Integer;
begin
   for j := 1 to 3 do
   begin
      k := State[0,j];
      State[0,j] := State[1,j];
      State[1,j] := State[2,j];
      State[2,j] := State[3,j];
      State[3,j] := k;
   end;
end;

// Realiza operaciones matriciales de intercambio de columnas
procedure ShiftCols(var State: TState);
var
   i,j,k : Integer;
begin
   for j := 1 to 3 do
   begin
      k := State[j,0];
      State[j,0] := State[j,1];
      State[j,1] := State[j,2];
      State[j,2] := State[j,3];
      State[j,3] := k;
   end;
end;

// Realiza operaciones matriciales inversas de intercambio de filas
procedure InvShiftRows(var State: TState);
var
   i,j,k : Integer;
begin
   for j := 1 to 3 do
   begin
      k := State[3,j];
      State[3,j] := State[2,j];
      State[2,j] := State[1,j];
      State[1,j] := State[0,j];
      State[0,j] := k;
   end;
end;

// Realiza operaciones matriciales inversas de intercambio de columnas
procedure InvShiftCols(var State: TState);
var
   i,j,k : Integer;
begin
   for j := 1 to 3 do
   begin
      k := State[j,3];
      State[j,3] := State[j,2];
      State[j,2] := State[j,1];
      State[j,1] := State[j,0];
      State[j,0] := k;
   end;
end;

// Convierte una cadena de carácteres ASCII a su equivalente Hexadecimal
function StringToHex(S : String): String;
var
   i: Integer;
begin
   for i := 1 to Length(S) do
      Result := Result + IntToHex(Ord(S[i]), 2);
end;

// Convierte una cadena de carácteres Hexadecimal a su equivalente ASCII
function HexToString(S : String): String;
var
   i : Integer;
begin
   for i := 1 to Length(S) do
      if ((i mod 2) = 1) then
         Result := Result + Chr(StrToInt('0x' + Copy(S, i, 2)));
end;

// Cifra un String por medio de una clave con operaciones matriciales y funciones lógicas
function Encode(DataStr, Key : String) : String;
var
   i : Integer;
   AuxStr : String;
   AuxKey : LongWord;
   Src, Dst : TStringStream;
   State : TState;

begin

   Src := TStringStream.Create(DataStr);
   Dst := TStringStream.Create('');

   FillChar(State,Sizeof(State),#0);

   while Src.Read(State,Sizeof(State)) > 0 do
   begin
      ShiftRows(State);
      ShiftCols(State);
      Dst.WriteBuffer(State,Sizeof(State));
      FillChar(State,Sizeof(State),#0);
   end;

   AuxKey := 0;

   for i := 1 to length(Key) do
      AuxKey := (AuxKey + ord(Key[i])) xor Length(Key);

   for i:=1 to length(Dst.DataString) do
      AuxStr := AuxStr + chr(ord(Dst.DataString[i]) xor AuxKey);

   Result := StringToHex(AuxStr);

end;

// Descifra un String por medio de una clave con operaciones matriciales y funciones lógicas
function Decode(DataStr, Key : String) : String;
var
   i : Integer;
   AuxStr : String;
   AuxKey : LongWord;
   Src, Dst : TStringStream;
   State : TState;

begin

   DataStr := HexToString(DataStr);

   Src := TStringStream.Create(DataStr);
   Dst := TStringStream.Create('');

   FillChar(State,Sizeof(State),#0);

   while Src.Read(State,Sizeof(State)) > 0 do
   begin
      InvShiftCols(State);
      InvShiftRows(State);
      Dst.WriteBuffer(State,Sizeof(State));
      FillChar(State,Sizeof(State),#0);
   end;

   AuxKey := 0;

   for i := 1 to length(Key) do
      AuxKey := (AuxKey + ord(Key[i])) xor Length(Key);

   for i:=1 to length(Dst.DataString) do
      AuxStr := AuxStr + chr(ord(Dst.DataString[i]) xor AuxKey);

   Result := AuxStr;

end;

// Llama la función que Cifra una cadena de carácteres
procedure TForm1.Button1Click(Sender: TObject);
begin
   Memo2.Text := Encode(Memo1.Text, Edit1.Text);
end;

// Llama la función que Descifra una cadena de carácteres
procedure TForm1.Button2Click(Sender: TObject);
begin
   Memo3.Text := Decode(Memo2.Text, Edit1.Text);
end;

// Reset los controles del formulario
procedure TForm1.Button3Click(Sender: TObject);
begin
   Edit1.Text := EmptyStr;
   Memo1.Clear;
   Memo2.Clear;
   Memo3.Clear;
end;

end.
El código anterior en Delphi 7 sobre Windows 7 Professional x32, Cifra y Descifra una cadena de caracteres por medio de una clave utilizando operaciones matriciales y funciones lógicas, (...)

Espero sea útil

Nelson.
Magnífico. Me lo apunto.

Yo hice un programita en C para cifrar datos, pero sólo funciona en binario. Vamos, que puede devolver cualquier cosa.
__________________
Proyectos actuales --> Allegro 5 Pascal ¡y Delphi!|MinGRo Game Engine
Responder Con Cita
  #16  
Antiguo 06-10-2014
Avatar de nlsgarcia
[nlsgarcia] nlsgarcia is offline
Miembro Premium
 
Registrado: feb 2007
Ubicación: Caracas, Venezuela
Posts: 2.206
Poder: 21
nlsgarcia Tiene un aura espectacularnlsgarcia Tiene un aura espectacular
Ñuño Martínez,

Cita:
Empezado por Ñuño Martínez
...Me lo apunto...


Revisa este código:
Código Delphi [-]
// NES (Nelson Encryption Standard )
// Cifra y Descifra Strings y Files

unit NES;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TState = Array[0..3,0..3] of Byte;

  function EncodeString(StringData, Key : String) : String;
  function DecodeString(StringData, Key : String) : String;
  function EncodeFile(FileName, Key : String) : Boolean;
  function DecodeFile(FileName, Key : String) : Boolean;
  
implementation

// Realiza operaciones matriciales de intercambio de filas
procedure ShiftRows(var State: TState);
var
   i,j,k : Integer;
begin
   for j := 1 to 3 do
   begin
      k := State[0,j];
      State[0,j] := State[1,j];
      State[1,j] := State[2,j];
      State[2,j] := State[3,j];
      State[3,j] := k;
   end;
end;

// Realiza operaciones matriciales de intercambio de columnas
procedure ShiftCols(var State: TState);
var
   i,j,k : Integer;
begin
   for j := 1 to 3 do
   begin
      k := State[j,0];
      State[j,0] := State[j,1];
      State[j,1] := State[j,2];
      State[j,2] := State[j,3];
      State[j,3] := k;
   end;
end;

// Realiza operaciones matriciales inversas de intercambio de filas
procedure InvShiftRows(var State: TState);
var
   i,j,k : Integer;
begin
   for j := 1 to 3 do
   begin
      k := State[3,j];
      State[3,j] := State[2,j];
      State[2,j] := State[1,j];
      State[1,j] := State[0,j];
      State[0,j] := k;
   end;
end;

// Realiza operaciones matriciales inversas de intercambio de columnas
procedure InvShiftCols(var State: TState);
var
   i,j,k : Integer;
begin
   for j := 1 to 3 do
   begin
      k := State[j,3];
      State[j,3] := State[j,2];
      State[j,2] := State[j,1];
      State[j,1] := State[j,0];
      State[j,0] := k;
   end;
end;

// Convierte una cadena de carácteres ASCII a su equivalente Hexadecimal
function StringToHex(S: String): String;
var
     i: Integer;
begin
   for i := 1 to Length(S) do
      Result := Result + IntToHex(Ord(S[i]), 2);
end;

// Convierte una cadena de carácteres Hexadecimal a su equivalente ASCII
function HexToString(S: String): String;
var
   i : Integer;
begin
   for i := 1 to Length(S) do
      if ((i mod 2) = 1) then
           Result := Result + Chr(StrToInt('0x' + Copy(S, i, 2)));
end;

// Cifra un String por medio de una clave con operaciones matriciales y funciones lógicas
function EncodeString(StringData, Key : String) : String;
var
   i : Integer;
   AuxStr : String;
   AuxKey : LongWord;
   StreamSrc, StreamDst : TStringStream;
   State : TState;

begin

   StreamSrc := TStringStream.Create(StringData);
   StreamDst := TStringStream.Create('');

   FillChar(State,Sizeof(State),#0);

   while StreamSrc.Read(State,Sizeof(State)) > 0 do
   begin
      ShiftRows(State);
      ShiftCols(State);
      StreamDst.WriteBuffer(State,Sizeof(State));
      FillChar(State,Sizeof(State),#0);
   end;

   AuxKey := 0;

   for i := 1 to length(Key) do
      AuxKey := (AuxKey + ord(Key[i])) xor Length(Key);

   for i:=1 to length(StreamDst.DataString) do
      AuxStr := AuxStr + chr(ord(StreamDst.DataString[i]) xor AuxKey);

   Result := StringToHex(AuxStr);

end;

// Descifra un String por medio de una clave con operaciones matriciales y funciones lógicas
function DecodeString(StringData, Key : String) : String;
var
   i : Integer;
   AuxStr : String;
   AuxKey : LongWord;
   StreamSrc, StreamDst : TStringStream;
   State : TState;

begin

   StringData := HexToString(StringData);

   StreamSrc := TStringStream.Create(StringData);
   StreamDst := TStringStream.Create('');

   FillChar(State,Sizeof(State),#0);

   while StreamSrc.Read(State,Sizeof(State)) > 0 do
   begin
      InvShiftCols(State);
      InvShiftRows(State);
      StreamDst.WriteBuffer(State,Sizeof(State));
      FillChar(State,Sizeof(State),#0);
   end;

   AuxKey := 0;

   for i := 1 to length(Key) do
      AuxKey := (AuxKey + ord(Key[i])) xor Length(Key);

   for i:=1 to length(StreamDst.DataString) do
      AuxStr := AuxStr + chr(ord(StreamDst.DataString[i]) xor AuxKey);

   Result := AuxStr;

end;

// Cifra un File por medio de una clave con operaciones matriciales y funciones lógicas
function EncodeFile(FileName, Key : String) : Boolean;
var
   i : Integer;
   S1, S2 : String;
   AuxKey : LongWord;
   FileSrc, FileDst : TFileStream;
   State : TState;
   AuxState : TStringStream;
   FileNameEnc : String;
   BytesRead : LongInt;

begin

   try

      try

         AuxKey := 0;

         for i := 1 to Length(Key) do
            AuxKey := (AuxKey + ord(Key[i])) xor Length(Key);

         FileSrc := TFileStream.Create(FileName, fmOpenRead);

         FileNameEnc := ExtractFilePath(FileName)
                        + ChangeFileExt(ExtractFileName(FileName),'')
                        + '_Enc'
                        + ExtractFileExt(FileName);

         FileDst := TFileStream.Create(FileNameEnc, fmCreate);
         FillChar(State,Sizeof(State),#0);

         BytesRead := FileSrc.Read(State,SizeOf(State));

         while BytesRead > 0 do
         begin

            S1 := EmptyStr;
            S2 := EmptyStr;

            if BytesRead = 16 then
            begin
               ShiftRows(State);
               ShiftCols(State);
            end;

            AuxState := TStringStream.Create('');
            AuxState.WriteBuffer(State,Sizeof(State));

            for i := 1 to BytesRead do
               S1 := S1 + chr(ord(AuxState.DataString[i]) xor AuxKey);

            S2 := StringToHex(S1);

            FileDst.Write(S2[1],Length(S2));

            FillChar(State,Sizeof(State),#0);
            AuxState.Free;

            BytesRead := FileSrc.Read(State,SizeOf(State));
            Application.ProcessMessages;

         end;

         Result := True;

      except

         Result := False;

      end;

   finally

      FileSrc.Free;
      FileDst.Free;

   end;

end;

// Cifra un File por medio de una clave con operaciones matriciales y funciones lógicas
function DecodeFile(FileName, Key : String) : Boolean;
var
   i : Integer;
   S1, S2, S3 : String;
   AuxKey : LongWord;
   FileSrc, FileDst : TFileStream;
   State : TState;
   AuxState : TStringStream;
   FileNameDec : String;
   AState : Array[0..31] of Char;
   BytesRead : LongInt;

begin

   if Pos('_Enc',FileName) = 0 then
      Exit;

   try

      try

         AuxKey := 0;

         for i := 1 to length(Key) do
            AuxKey := (AuxKey + ord(Key[i])) xor Length(Key);

         FileSrc := TFileStream.Create(FileName, fmOpenRead);
         FileNameDec := StringReplace(FileName,'_Enc','_Dec',[]);

         FileDst := TFileStream.Create(FileNameDec, fmCreate);

         FillChar(State,Sizeof(State),#0);
         FillChar(AState,Sizeof(AState),#0);

         BytesRead := FileSrc.Read(AState,Length(AState));

         while BytesRead > 0 do
         begin

            S1 := EmptyStr;
            S2 := EmptyStr;
            S3 := EmptyStr;

            S1 := Copy(AState,0, BytesRead);
            S2 := HexToString(S1);

            Move(S2[1], State[0,0], Length(S2));

            if BytesRead = 32 then
            begin
               InvShiftCols(State);
               InvShiftRows(State);
            end;

            AuxState := TStringStream.Create('');
            AuxState.WriteBuffer(State,Sizeof(State));

            for i := 1 to BytesRead div 2 do
               S3 := S3 + chr(ord(AuxState.DataString[i]) xor AuxKey);

            FileDst.Write(S3[1],Length(S3));

            FillChar(State,Sizeof(State),#0);
            FillChar(AState,Length(AState),#0);
            AuxState.Free;

            BytesRead := FileSrc.Read(AState,Length(AState));
            Application.ProcessMessages;

         end;

         Result := True;

      except

         Result := False;

      end;

   finally

      FileSrc.Free;
      FileDst.Free;

   end;

end;

end.
Código Delphi [-]
// Ejemplo de uso de NES (Nelson Encryption Standard )

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Memo1: TMemo;
    Memo2: TMemo;
    Memo3: TMemo;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Button4: TButton;
    Button5: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure Button5Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

Uses NES;

// Llama la función que Cifra una cadena de carácteres
procedure TForm1.Button1Click(Sender: TObject);
begin
   Memo2.Text := EncodeString(Memo1.Text, Edit1.Text);
end;

// Llama la función que Descifra una cadena de carácteres
procedure TForm1.Button2Click(Sender: TObject);
begin
   Memo3.Text := DecodeString(Memo2.Text, Edit1.Text);
end;

// Reset los controles del formulario
procedure TForm1.Button3Click(Sender: TObject);
begin
   Edit1.Text := EmptyStr;
   Memo1.Clear;
   Memo2.Clear;
   Memo3.Clear;
end;

// Llama la función que Cifra una Archivo
procedure TForm1.Button4Click(Sender: TObject);
var
  openDialog : TOpenDialog;
  MsgUser : String;

begin

   openDialog := TOpenDialog.Create(self);
   openDialog.InitialDir := GetCurrentDir;
   openDialog.Options := [ofFileMustExist];
   openDialog.Filter := 'Files |*.*';

   if openDialog.Execute then
   begin

      Button4.Enabled := False;
      Button5.Enabled := False;

      if EncodeFile(openDialog.FileName, Edit1.Text) then
      begin
         MsgUser := Format('El Archivo %s fue Cifrado',[openDialog.FileName]);
         MessageDlg(MsgUSer,mtInformation,[mbOK],0)
      end
      else
      begin
         MsgUser := Format('Error en el Cifrado del Archivo %s',[openDialog.FileName]);
         MessageDlg(MsgUSer,mtError,[mbOK],0)
      end;

      Button4.Enabled := True;
      Button5.Enabled := True;

   end;

end;

// Llama la función que Descifra una Archivo
procedure TForm1.Button5Click(Sender: TObject);
var
  openDialog : TOpenDialog;
  MsgUser : String;

begin

   openDialog := TOpenDialog.Create(self);
   openDialog.InitialDir := GetCurrentDir;
   openDialog.Options := [ofFileMustExist];
   openDialog.Filter := 'Files |*.*';

   if openDialog.Execute then
   begin

      Button4.Enabled := False;
      Button5.Enabled := False;

      if DecodeFile(openDialog.FileName, Edit1.Text) then
      begin
         MsgUser := Format('El Archivo %s fue Descifrado',[openDialog.FileName]);
         MessageDlg(MsgUSer,mtInformation,[mbOK],0)
      end
      else
      begin
         MsgUser := Format('Error en el Descifrado del Archivo %s',[openDialog.FileName]);
         MessageDlg(MsgUSer,mtError,[mbOK],0)
      end;

      Button4.Enabled := True;
      Button5.Enabled := True;

   end;

end;

end.
El código anterior en Delphi 7 sobre Windows 7 Professional x32 es la versión 2 del código propuesto en el Msg #20 el cual permite, Cifrar y Descifrar Strings y Archivos por medio de una clave utilizando operaciones matriciales y funciones lógicas, según se muestra en las siguientes imágenes:











El código del ejemplo esta disponible en : NES (Nelson Encryption Standard ).rar

Notas:

1- El algoritmo NES permite, cifrar Strings y Archivos en una secuencia de caracteres hexadecimales.

2- Cuando se cifra un archivo, se crea uno nuevo con el nombre original mas el sufijo '_Enc', ejemplo: File.txt -> Función EncodeFile -> File_Enc.txt

3- Cuando se descifra un archivo, se crea uno nuevo al cual se le cambia el sufijo '_Enc' por '_Dec', ejemplo: File_Enc.txt -> Función DecodeFile -> File_Dec.txt

4- El archivo original nunca es modificado ni borrado, lo cual garantiza las pruebas con el algoritmo y flexibiliza su implementación.

5- El código propuesto es útil como una opción de cifrado/descifrado de Strings y Archivos, sin embargo si los requerimientos de la aplicación lo ameritan, sugiero implementar el algoritmo Advanced Encryption Standard (AES) (Msg #16), el cual a sido adoptado como : El estándar de cifrado por el gobierno de los Estados Unidos.

Espero sea útil

Nelson.
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro


La franja horaria es GMT +2. Ahora son las 05:06:57.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi