Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Encriptación y desencriptación de datos (https://www.clubdelphi.com/foros/showthread.php?t=44398)

mcalmanovici 05-06-2007 18:57:27

Encriptación y desencriptación de datos
 
Hola gente:
Mi objetivo es encriptar y desencriptar un dato que viene desde la base de datos... Yo hago una consulta y traigo el dato de la tabla correspondiente.
Ahora bien sé que con los componentes DES y SHA1 debería poder hacerlo.
Realmente estuvo buscando en internet y no encuentro información al respecto.
Asimismo una vez que lo desencripto quiero poder mostrarlo en una grilla este dato.
Espero haberme expresado bien para que me entiendan.
Si alguno puede ayudarme le estaré muy agradecido.
Saludos.
Mariano.

droguerman 05-06-2007 20:10:43

esteeee no.

SHA1, DES y MD5 son algoritmos no reversibles es decir encriptan no desencriptan, te recomendaria que busques información sobre RSA

jachguate 05-06-2007 20:28:40

Un método sencillo para encriptar/desencriptar es el algoritmo XorEncode/XorDecode, que no es de clave pública, pero creo que vale para tu caso.

Si tenes instalado el proyecto JEDI, hay una implementación en la unidad JvStrUtils, que en mi caso está en la carpeta jvcl\archive

Hasta luego.

;)

ppb 05-06-2007 20:29:41

Cita:

Empezado por droguerman
esteeee no.

SHA1, DES y MD5 son algoritmos no reversibles es decir encriptan no desencriptan, te recomendaria que busques información sobre RSA

Una aclaración SHA1 y MD5 son algoritmos "hash" , no son para encrip/descrip. EL DES es un algoritmo encrip/descrip de clave simétrica.

Salu2.

seoane 05-06-2007 20:46:21

Ahora mismo se utiliza bastante AES, y creo que por ahí andaba una librería para utilizarlo en delphi. También puedes mirar algo sobre encriptacion de curva elíptica, que también esta muy de moda.

Si no te esta persiguiendo la CIA :p , también puedes usar métodos mas sencillos. Aquí te dejo un poco de código que cree de hace algún tiempo, utiliza el algoritmo RC4 y solo utiliza funciones de la API de windows.
Código Delphi [-]
type
  HCRYPTPROV  = ULONG;
  PHCRYPTPROV = ^HCRYPTPROV;
  HCRYPTKEY   = ULONG;
  PHCRYPTKEY  = ^HCRYPTKEY;
  HCRYPTHASH  = ULONG;
  PHCRYPTHASH = ^HCRYPTHASH;
  LPAWSTR     = PAnsiChar;
  ALG_ID      = ULONG;

const
  CRYPT_NEWKEYSET = $00000008;
  PROV_RSA_FULL   = 1;
  ALG_TYPE_ANY    = 0;
  ALG_CLASS_HASH  = (4 shl 13);
  ALG_SID_MD5     = 3;
  CALG_MD5        = (ALG_CLASS_HASH or ALG_TYPE_ANY or ALG_SID_MD5);
  HP_HASHVAL      = $0002;
  ALG_CLASS_DATA_ENCRYPT = (3 shl 13);
  ALG_TYPE_STREAM = (4 shl 9);
  ALG_SID_RC4     = 1;
  CALG_RC4        = (ALG_CLASS_DATA_ENCRYPT or ALG_TYPE_STREAM or ALG_SID_RC4);


  function CryptAcquireContext(phProv       :PHCRYPTPROV;
                               pszContainer :LPAWSTR;
                               pszProvider  :LPAWSTR;
                               dwProvType   :DWORD;
                               dwFlags      :DWORD) :BOOL; stdcall;
    external ADVAPI32 name 'CryptAcquireContextA';
  function CryptCreateHash    (hProv   :HCRYPTPROV;
                               Algid   :ALG_ID;
                               hKey    :HCRYPTKEY;
                               dwFlags :DWORD;
                               phHash  :PHCRYPTHASH) :BOOL;stdcall;
    external ADVAPI32 name 'CryptCreateHash';
  function CryptHashData      (hHash             :HCRYPTHASH;
                               const pbData      :PBYTE;
                               dwDataLen         :DWORD;
                               dwFlags           :DWORD) :BOOL;stdcall;
    external ADVAPI32 name 'CryptHashData';
  function CryptEncrypt       (hKey       :HCRYPTKEY;
                               hHash      :HCRYPTHASH;
                               Final      :BOOL;
                               dwFlags    :DWORD;
                               pbData     :PBYTE;
                               pdwDataLen :PDWORD;
                               dwBufLen   :DWORD) :BOOL;stdcall;
    external ADVAPI32 name 'CryptEncrypt';
  function CryptDecrypt       (hKey       :HCRYPTKEY;
                               hHash      :HCRYPTHASH;
                               Final      :BOOL;
                               dwFlags    :DWORD;
                               pbData     :PBYTE;
                               pdwDataLen :PDWORD) :BOOL;stdcall;
    external ADVAPI32 name 'CryptDecrypt';
  function CryptDeriveKey     (hProv     :HCRYPTPROV;
                               Algid     :ALG_ID;
                               hBaseData :HCRYPTHASH;
                               dwFlags   :DWORD;
                               phKey     :PHCRYPTKEY) :BOOL;stdcall;
    external ADVAPI32 name 'CryptDeriveKey'; 
  function CryptDestroyHash   (hHash:HCRYPTHASH) :BOOL;stdcall;
    external ADVAPI32 name 'CryptDestroyHash';
  function CryptReleaseContext(hProv:HCRYPTPROV; dwFlags:DWORD):BOOL;stdcall;
    external ADVAPI32 name 'CryptReleaseContext';

function Cifrar(Texto, Password: string): string;
var
  hProv: HCRYPTPROV;
  hHash: HCRYPTHASH;
  hKey:  HCRYPTKEY;
  Success: BOOL;
  Buffer: array[0..1024] of Char;
  DataLen: DWORD;
  i: Integer;
begin
  Result:= '';
  Success:= CryptAcquireContext(@hProv, nil, nil, PROV_RSA_FULL, 0);
  if (not Success) then
    if GetLastError() = DWORD(NTE_BAD_KEYSET) then
      Success:= CryptAcquireContext(@hProv, nil, nil, PROV_RSA_FULL, CRYPT_NEWKEYSET);
  if Success then
    begin
      if CryptCreateHash(hProv, CALG_MD5, 0, 0, @hHash) then
        begin
          if CryptHashData(hHash, PByte(PChar(Password)), Length(Password), 0) then
            if CryptDeriveKey(hProv, CALG_RC4, hHash, $00800000, @hKey) then
            begin
              FillChar(Buffer,Sizeof(Buffer),0);
              StrLCopy(@Buffer,PChar(Texto),Sizeof(Buffer) - 1);
              DataLen:= StrLen(@Buffer);
              if CryptEncrypt(hKey, 0, TRUE, 0, PByte(@Buffer), @DataLen, Sizeof(Buffer)) then
              begin
                for i:= 0 to DataLen - 1 do
                  Result:= Result + IntToHex(Byte(Buffer[i]),2);
              end;
            end;
          CryptDestroyHash(hHash);
        end;
      CryptReleaseContext(hProv,0);
    end;
end;

function Descifrar(Texto, Password: string): string;
var
  hProv: HCRYPTPROV;
  hHash: HCRYPTHASH;
  hKey:  HCRYPTKEY;
  Success: BOOL;
  Buffer: array[0..1024] of Char;
  DataLen: DWORD;
  i,j: Integer;
begin
  Result:= '';
  if Length(Texto) = 0 then
    Exit;
  if Odd(Length(Texto)) then
    Exit;
  if (Length(Texto) shr 2) > (Sizeof(Buffer) - 1) then
    Exit;
  i:= 0;
  FillChar(Buffer,Sizeof(Buffer),0);
  while Length(Texto) > 0 do
  begin
    if TryStrToInt('$'+copy(Texto,1,2),j) then
    begin
      Buffer[i]:= Char(j);
      Delete(Texto,1,2);
      inc(i);
    end else Exit;
  end;
  Success:= CryptAcquireContext(@hProv, nil, nil, PROV_RSA_FULL, 0);
  if (not Success) then
    if GetLastError() = DWORD(NTE_BAD_KEYSET) then
      Success:= CryptAcquireContext(@hProv, nil, nil, PROV_RSA_FULL, CRYPT_NEWKEYSET);
  if Success then
    begin
      if CryptCreateHash(hProv, CALG_MD5, 0, 0, @hHash) then
        begin
          if CryptHashData(hHash, PByte(PChar(Password)), Length(Password), 0) then
            if CryptDeriveKey(hProv, CALG_RC4, hHash, $00800000, @hKey) then
            begin
              DataLen:= i;
              if CryptDecrypt(hKey, 0, TRUE, 0, PByte(@Buffer), @DataLen) then
              begin
                Result:= Copy(String(PChar(@Buffer)),1,DataLen);
              end;
            end;
          CryptDestroyHash(hHash);
        end;                          
      CryptReleaseContext(hProv,0);
    end;
end;

BuenaOnda 05-06-2007 20:47:18

hola m ira este hilo http://www.clubdelphi.com/foros/show...light=encripta a lo mejor te puede servir, ahi adjunte unos componentes para encriptacion..;)

jachguate 05-06-2007 20:50:54

Buscando un poco, también encontré esto:

http://www.scramdisk.clara.net/d_crypto.html

Saludos.

sviga 14-07-2008 05:28:07

Error algoritmo de seoane con CryptAcquireContex
 
hola tuve un error con la api de windows CryptAcquireContext en otra maquina El error que me arroja es el siguiente
ErrNumber: --2146893792 (0x80090020)


Alguno tiene alguna idea

Gracias:)

seoane 14-07-2008 20:17:38

Cita:

Empezado por sviga (Mensaje 300228)
hola tuve un error con la api de windows CryptAcquireContext en otra maquina El error que me arroja es el siguiente
ErrNumber: --2146893792 (0x80090020)

Pues no se me ocurre que puede ser, la descripción del error según windows es "Error interno", lo que no aclara mucho. ¿Estas usando el código tal cual o lo has modificado?

Por otro lado, si esta interesado en cifrar texto te recomiendo el algoritmo AES. Aquí lo tienes completamente implementado en delphi, sin necesidad de librerías externas:
http://delphi.jmrds.com/?q=node/44

Y si lo que queires es cifrar archivos:
http://delphi.jmrds.com/?q=node/31

sviga 15-07-2008 15:34:47

Recien lo vi, que rapido contestaste. Muchas gracias !!!


Estaba mirando el codigo delAES esta muy bueno y ya esta todo resuelto, fenomenal:). Lo que estoy es tratar de llevarlo a .net porque tengo que realizarlo en delphi .net


La franja horaria es GMT +2. Ahora son las 17:21:02.

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