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 19-06-2012
JoseSagas JoseSagas is offline
Miembro
NULL
 
Registrado: jun 2012
Posts: 33
Poder: 0
JoseSagas Va por buen camino
encriptar y desencriptar

alguien sabe como encriptar y desencriptar? gracias por la ayuda
Responder Con Cita
  #2  
Antiguo 19-06-2012
Avatar de Casimiro Notevi
Casimiro Notevi Casimiro Notevi is offline
Moderador
 
Registrado: sep 2004
Ubicación: En algún lugar.
Posts: 32.039
Poder: 10
Casimiro Notevi Tiene un aura espectacularCasimiro Notevi Tiene un aura espectacular
Por favor, JoseSagas, sabemos que eres nuevo por aquí, así que te recomendamos que leas nuestra guía de estilo.
Es muy simple, se recomiendan varias cositas, entre ellas la de poner un título descriptivo a las preguntas, también que antes de preguntar... ¡¡¡usa la opción de "buscar"!!!, y si no encuentras nada entonces pregunta.
Además que no sean preguntas "generales", ¿qué crees que se puede contestar a tu pregunta?:
Tu pregunta: alguien sabe como encriptar y desencriptar?
Respuesta: Sí.

Gracias por tu colaboración.
Responder Con Cita
  #3  
Antiguo 19-06-2012
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
Pues yo no se desencriptar... ba, nunca lo intenté y no se si hasta es ilegal... eso de ir un cementerio y sacar o poner de una cripta como que no es lo mío.

Creo que lo que has intentado decir es cifrar y descifrar

Saludos,
__________________
Delphius
[Guia de estilo][Buscar]
Responder Con Cita
  #4  
Antiguo 20-06-2012
Avatar de duilioisola
[duilioisola] duilioisola is offline
Miembro Premium
 
Registrado: ago 2007
Ubicación: Barcelona, España
Posts: 1.734
Poder: 20
duilioisola Es un diamante en brutoduilioisola Es un diamante en brutoduilioisola Es un diamante en bruto
Si, yo se como encriptar y desencriptar!

Para encriptar:
Cojes la letra siguiente a la que toca. si es la Z cojes la A.
Ejemplo: Encriptar('IBM') = 'HAL'

Para desencriptar:
Cojes la letra anterior a la que toca. si es la A cojes la Z.
Ejemplo: Encriptar('HAL') = 'IBM'
Responder Con Cita
  #5  
Antiguo 20-06-2012
cecam cecam is offline
Miembro
 
Registrado: may 2006
Ubicación: Girona
Posts: 47
Poder: 0
cecam Va por buen camino
http://sourceforge.net/projects/tplockbox/

Para algo mas sencillo, hay trucos en clubdelphi
http://www.clubdelphi.com/trucos/ind...ll=0&scrollb=0
http://www.clubdelphi.com/trucos/ind...ll=0&scrollb=0


Saludos!
Responder Con Cita
  #6  
Antiguo 20-06-2012
Avatar de newtron
[newtron] newtron is offline
Membrillo Premium
 
Registrado: abr 2007
Ubicación: Motril, Granada
Posts: 3.462
Poder: 21
newtron Va camino a la fama
Menos mal que hay alguien serio en este foro.
__________________
Be water my friend.
Responder Con Cita
  #7  
Antiguo 20-06-2012
Northern Northern is offline
Miembro
 
Registrado: ene 2006
Posts: 211
Poder: 19
Northern Va por buen camino
Esas dos palabras no existen en el idioma español. Existe cifrar, codificar, enmarañar, ofuscar, etc. pero encriptar y desencriptar no aún no han sido aceptadas.
Responder Con Cita
  #8  
Antiguo 20-06-2012
Avatar de Casimiro Notevi
Casimiro Notevi Casimiro Notevi is offline
Moderador
 
Registrado: sep 2004
Ubicación: En algún lugar.
Posts: 32.039
Poder: 10
Casimiro Notevi Tiene un aura espectacularCasimiro Notevi Tiene un aura espectacular
Sin embargo, sí viene criptografía.
Responder Con Cita
  #9  
Antiguo 20-06-2012
Loviedo Loviedo is offline
Miembro
 
Registrado: dic 2004
Posts: 214
Poder: 0
Loviedo cantidad desconocida en este momento
Diccionario Informático:
Encriptar
es la acción de proteger información para que no pueda ser leída sin una clave. Sinónimos de Encriptar: cifrar, codificar.

Saludos.
Responder Con Cita
  #10  
Antiguo 20-06-2012
Avatar de Casimiro Notevi
Casimiro Notevi Casimiro Notevi is offline
Moderador
 
Registrado: sep 2004
Ubicación: En algún lugar.
Posts: 32.039
Poder: 10
Casimiro Notevi Tiene un aura espectacularCasimiro Notevi Tiene un aura espectacular
¿Qué diccionario es ese?, ¿quién lo ha escrito?

Bueno, todos sabemos lo que es encriptar/desencriptar. El único problema es que el usuario que inició este hilo preguntó:

> alguien sabe como encriptar y desencriptar? gracias por la ayuda .

Y ante esa pregunta sólo cabe una respuesta: Sí, alguien sabe.
Responder Con Cita
  #11  
Antiguo 20-06-2012
Avatar de mamcx
mamcx mamcx is offline
Moderador
 
Registrado: sep 2004
Ubicación: Medellín - Colombia
Posts: 3.911
Poder: 25
mamcx Tiene un aura espectacularmamcx Tiene un aura espectacularmamcx Tiene un aura espectacular
Usar MD5 para encriptar ya esta desacreditado.
__________________
El malabarista.
Responder Con Cita
  #12  
Antiguo 20-06-2012
Avatar de duilioisola
[duilioisola] duilioisola is offline
Miembro Premium
 
Registrado: ago 2007
Ubicación: Barcelona, España
Posts: 1.734
Poder: 20
duilioisola Es un diamante en brutoduilioisola Es un diamante en brutoduilioisola Es un diamante en bruto
Estos son ejemplos para calcular un HASH, por lo que no son ejemplos de encriptación

Para cifrar o descifrar puedes mirar este ejemplo.

Mira estos dos links que te envían a la web de Seoane para cifrar strings o archivos.
strings: delphi.jmrds.com/?q=node/44
archivos: delphi.jmrds.com/?q=node/70
Responder Con Cita
  #13  
Antiguo 20-06-2012
Avatar de mamcx
mamcx mamcx is offline
Moderador
 
Registrado: sep 2004
Ubicación: Medellín - Colombia
Posts: 3.911
Poder: 25
mamcx Tiene un aura espectacularmamcx Tiene un aura espectacularmamcx Tiene un aura espectacular
Es correcto. MD5 es para hash, no encriptar.

Una exelente introduccion al tema:

http://coding.smashingmagazine.com/2...phy-made-easy/
__________________
El malabarista.
Responder Con Cita
  #14  
Antiguo 20-06-2012
JoseSagas JoseSagas is offline
Miembro
NULL
 
Registrado: jun 2012
Posts: 33
Poder: 0
JoseSagas Va por buen camino
muchas gracias a todos por su ayuda, me ayudaron mucho
Responder Con Cita
  #15  
Antiguo 20-06-2012
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
Cita:
Empezado por Loviedo Ver Mensaje
Diccionario Informático:
Encriptar
es la acción de proteger información para que no pueda ser leída sin una clave. Sinónimos de Encriptar: cifrar, codificar.

Saludos.
Encriptar y desencriptar son las dos peores palabras que el spanglish ha producido. NO me vengas con eso del diccionario informático. Agarrá cualquier artículo serio sobre criptografía en español y leerás el término correcto: cifrado y descifrado.
Suena asqueroso encriptar y desencriptar... Tenemos otras palabras mejores en nuestro idioma. De que existan palabras ya aceptadas en el inglés y la hayamos adoptado para la jerga informática no te lo discuto pero de allí a que se haya aceptado y popularizado esas dos engendros de poner y sacar de una cripta es todo un error como si fuera un sinónimo de cifrar y descifrar. Estás muy equivocado.
Hay que corregir ese mal hablar, seamos más profesionales por favor.

Como ha dicho Casimiro, existe el término criptografía que es la ciencia, cuya raíz compartimos con el inglés debido a que compartimos el mismo origen: latín. Más la acción es cifrar y descifrar. Que en inglés se le diga Encrypt no da derecho ni implica que en español aplique la misma regla y pueda decirse a sus anchas.

Saludos,
__________________
Delphius
[Guia de estilo][Buscar]
Responder Con Cita
  #16  
Antiguo 20-06-2012
Avatar de dec
dec dec is offline
Moderador
 
Registrado: dic 2004
Ubicación: Alcobendas, Madrid, España
Posts: 13.107
Poder: 34
dec Tiene un aura espectaculardec Tiene un aura espectacular
Hola,

Queden aquí también este par de unidades, basadas ambas en el trabajo de nuestro compañero Domingo Seoane.

Código Delphi [-]
{
  ©2012 David Esperalta (davidesperalta@gmail.com)

  Basado en la unidad "Hashes.pas" de Domingo Seoane
  (http://www.clubdelphi.com/foros/member.php?u=2375)
}

unit UCipher;

interface

uses
  SysUtils, Classes;

const
  DEFAULT_KBBUFFER = 10240;

type
  EUknowAlgorithmException = class( Exception );
  TOnWork = procedure( sender : TObject; progress : int64 ) of object;
  THashAlgorithm = ( haMD5, haSHA1, haSHA256, haSHA384, haSHA512, haUnknow );
  TOnWorkBegin = procedure( sender : TObject; maxProgress : int64 ) of object;

type
  TCipher = class( TObject )
  private
    FAbort: boolean;
    FOnWork: TOnWork;
    FWorking: boolean;
    FKBBuffer: integer;
    FOnAbort: TNotifyEvent;
    FOnError: TNotifyEvent;
    FOnWorkEnd: TNotifyEvent;
    FOnWorkBegin: TOnWorkBegin;
  private
    procedure SetKBBuffer( value : integer );
    procedure DoCryptDecryptStream( source, target: TStream;
     password : string; algorithm : THashAlgorithm; toCrypt : boolean );
  public
    procedure Abort();
    constructor Create();
  public
    function EncryptString( const str, password : string; algorithm : THashAlgorithm ) : string;
    function DecryptString( const str, password : string; algorithm : THashAlgorithm ) : string;
    procedure EncryptStream( source, target : TStream; password : string; algorithm : THashAlgorithm );
    procedure DecryptStream( source, target : TStream; password : string; algorithm : THashAlgorithm );
    procedure EncryptFile( const sourcePath, targetPath, password : string; algorithm : THashAlgorithm );
    procedure DecryptFile( const sourcePath, targetPath, password : string; algorithm : THashAlgorithm );
  public
    property Working: boolean read FWorking;
    property OnWork: TOnWork read FOnWork write FOnWork;
    property OnAbort: TNotifyEvent read FOnAbort write FOnAbort;
    property OnError : TNotifyEvent read FOnError write FOnError;
    property OnWorkEnd: TNotifyEvent read FOnWorkEnd write FOnWorkEnd;
    property OnWorkBegin: TOnWorkBegin read FOnWorkBegin write FOnWorkBegin;
    property KBBuffer: integer read FKBBuffer write SetKbBuffer default DEFAULT_KBBUFFER;
  end;

implementation

uses
  Windows;

type
  ALG_ID = ULONG;
  HCRYPTKEY = ULONG;
  HCRYPTHASH = ULONG;
  HCRYPTPROV = ULONG;
  LPAWSTR = PAnsiChar;
  PHCRYPTKEY = ^HCRYPTKEY;
  PHCRYPTPROV = ^HCRYPTPROV;
  PHCRYPTHASH = ^HCRYPTHASH;

const
  PROV_RSA_AES = 24;
  CALG_RC4 = $6801;
  HP_HASHVAL = $0002;
  HP_HASHSIZE = $0004;
  CALG_MD5 = $00008003;
  CALG_MD4 = $00008002;
  CALG_SHA1  = $00008004;
  CALG_SHA_256 = $0000800c;
  CALG_SHA_384 = $0000800d;
  CALG_SHA_512 = $0000800e;
  CRYPT_NEWKEYSET = $00000008;
  CRYPT_VERIFYCONTEXT  = $F0000000;

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 CryptGetHashParam
(
  hHash : HCRYPTHASH;
  dwParam : DWORD;
  pbData : PBYTE;
  pdwDataLen : PDWORD;
  dwFlags : DWORD
) : BOOL; stdcall;
external ADVAPI32 name 'CryptGetHashParam';

function CryptDestroyHash
(
  hHash : HCRYPTHASH
) : BOOL; stdcall;
external ADVAPI32 name 'CryptDestroyHash';

function CryptReleaseContext
(
  hProv : HCRYPTPROV;
  dwFlags : DWORD
) : BOOL; stdcall;
external ADVAPI32 name 'CryptReleaseContext';

function CryptDeriveKey
(
  hProv : HCRYPTPROV;
  Algid : ALG_ID;
  hBaseData : HCRYPTHASH;
  dwFlags : DWORD;
  phKey : PHCRYPTKEY
) : BOOL; stdcall ;
external ADVAPI32 name 'CryptDeriveKey';

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';

{ TCipher }

constructor TCipher.Create();
begin
  inherited Create();
  FAbort := false;
  FWorking := false;
  FKBBuffer := DEFAULT_KBBUFFER;
end;

procedure TCipher.Abort();
begin
  FAbort := true;
  FWorking := false;
end;

procedure TCipher.SetKBBuffer( value : integer );
begin
  if value <> FKBBuffer then
  begin
    if value >= 0 then
      FKBBuffer := value
    else
      FKBBuffer := DEFAULT_KBBUFFER;
  end;
end;

procedure TCipher.EncryptFile(const sourcePath, targetPath, password: string; algorithm : THashAlgorithm );
var
  source, target : TFileStream;
begin
  if FileExists( sourcePath ) then
  begin
    source := TFileStream.Create( sourcePath, fmOpenRead );
    target := TFileStream.Create( targetPath, fmCreate );
    try
      DoCryptDecryptStream( source, target, password, algorithm, true );
    finally
      source.Free();
      target.Free();
    end;
  end;
end;

procedure TCipher.DecryptFile(const sourcePath, targetPath, password: string; algorithm : THashAlgorithm);
var
  source, target : TFileStream;
begin
  if FileExists( sourcePath ) then
  begin
    source := TFileStream.Create( sourcePath, fmOpenRead );
    target := TFileStream.Create( targetPath, fmCreate );
    try
      DoCryptDecryptStream( source, target, password, algorithm, false );
    finally
      source.Free();
      target.Free();
    end;
  end;
end;

procedure TCipher.EncryptStream( source, target : TStream; password : string; algorithm : THashAlgorithm );
begin
  DoCryptDecryptStream( source, target, password, algorithm, true );
end;

procedure TCipher.DecryptStream( source, target : TStream; password : string; algorithm : THashAlgorithm );
begin
  DoCryptDecryptStream( source, target, password, algorithm, false );
end;

function TCipher.EncryptString(const str, password: string; algorithm : THashAlgorithm ): string;
var
  source, target : TStringStream;
begin
  result := '';

  source := TStringStream.Create( str );
  target := TStringStream.Create( '' );
  try
    DoCryptDecryptStream( source, target, password, algorithm, true );
    result := target.DataString;
  finally
    source.Free();
    target.Free();
  end;
end;

function TCipher.DecryptString(const str, password: string; algorithm : THashAlgorithm ): string;
var
  source, target : TStringStream;
begin
  result := '';

  source := TStringStream.Create( str );
  target := TStringStream.Create( '' );
  try
    DoCryptDecryptStream( source, target, password, algorithm, false );
    result := target.DataString;
  finally
    source.Free();
    target.Free();
  end;
end;

procedure TCipher.DoCryptDecryptStream( source, target: TStream;
 password : string; algorithm : THashAlgorithm; toCrypt : boolean );
var
  buffer : PByte;
  key : HCRYPTKEY;
  bytesRead : dWord;
  hashAlgId : ALG_ID;
  readPosition : longint;
  hProvider : HCRYPTPROV;
  hashAddress : HCRYPTHASH;
  successQuery, endOfStream : boolean;
begin
  successQuery := CryptAcquireContext
  (
    @hProvider,
    nil,
    nil,
    PROV_RSA_AES, CRYPT_VERIFYCONTEXT
  );

  if not successQuery then
  begin
    if GetLastError() = DWORD( NTE_BAD_KEYSET ) then
    begin
      successQuery := CryptAcquireContext
      (
        @hProvider,
        nil,
        nil,
        PROV_RSA_AES,
        CRYPT_NEWKEYSET
      );
    end;
  end;

  if successQuery then
  begin

    case algorithm of
      haMD5 : hashAlgId := CALG_MD5;
      haSHA1 : hashAlgId := CALG_SHA1;
      haSHA256 : hashAlgId := CALG_SHA_256;
      haSHA384 : hashAlgId := CALG_SHA_384;
      haSHA512 : hashAlgId := CALG_SHA_512;
    else
      raise EUknowAlgorithmException.Create( 'Unknow hash algorithm' );
    end;

    if CryptCreateHash( hProvider, hashAlgId, 0, 0, @hashAddress ) then
    begin
      FAbort := false;
      FWorking := true;
      readPosition := 0;

      if Assigned(FOnWorkBegin) then
        FOnWorkBegin( self, source.Size);

      if CryptHashData( hashAddress, @password[ 1 ], Length( password ), 0 ) then
      begin
        if CryptDeriveKey( hProvider, CALG_RC4, hashAddress, 0, @key ) then
        begin
          CryptDestroyHash( hashAddress );

          GetMem( buffer, FKBBuffer );

          repeat
            endOfStream := source.Position >= source.Size;

            if not endOfStream then
            begin
              bytesRead := source.Read( buffer^, FKBBuffer );

              Inc( readPosition, bytesRead );

              if toCrypt then
                CryptEncrypt( key, 0, endOfStream, 0, buffer, @bytesRead, bytesRead )
              else
                CryptDecrypt( key, 0, endOfStream, 0, buffer, @bytesRead );

              target.Write( buffer^, bytesRead );

              if Assigned( FOnWork ) then
                FOnWork( self, readPosition );
            end;

          until FAbort or endOfStream;

          FreeMem( buffer, FKBBuffer );

          if FAbort then
          begin
            if Assigned( FOnAbort )
              then FOnAbort( Self );
          end;
          
        end
    else
    begin
          if Assigned( FOnError ) then
            FOnError( self );    
    end;
      end;
    end
  else
  begin
      if Assigned( FOnError ) then
        FOnError( self );
  end;
  
    CryptReleaseContext( hProvider, 0 );
  end
  else
  begin
    if Assigned( FOnError ) then
      FOnError( self );
  end;

  FWorking := false;

  if not FAbort and Assigned( FOnWorkEnd ) then
    FOnWorkEnd( self );
end;

end.

Código Delphi [-]
{
  ©2012 David Esperalta (davidesperalta@gmail.com)

  Basado en la unidad "Hashes.pas" de Domingo Seoane
  (http://www.clubdelphi.com/foros/member.php?u=2375)
}

unit UHashes;

interface

uses
  SysUtils, Classes;

const
  DEFAULT_KBBUFFER = 10240;

type
  EUknowAlgorithmException = class( Exception );
  THashAlgorithm = ( haMD5, haSHA1, haSHA256, haSHA384, haSHA512, haUnknow );
  TOnWork = procedure( sender : TObject; progress : int64 ) of object;
  TOnWorkBegin = procedure( sender : TObject; maxProgress : int64 ) of object;

type
  THashes = class( TObject )
  private
    FAbort: boolean;
    FOnWork: TOnWork;
    FWorking: boolean;
    FKBBuffer: integer;
    FOnAbort: TNotifyEvent;
    FOnError: TNotifyEvent;
    FOnWorkEnd: TNotifyEvent;
    FOnWorkBegin: TOnWorkBegin;
  private
    procedure SetKBBuffer( value : integer );
  public
    procedure Abort();
    constructor Create();
    function CalcStringHash( str: string; algorithm : THashAlgorithm ) : string;
    function CalcFileHash( filePath : string; algorithm : THashAlgorithm ) : string;
    function CalcStreamHash( stream: TStream; algorithm : THashAlgorithm ) : string;
  public
    property Working: boolean read FWorking;
  public
    property OnWork: TOnWork read FOnWork write FOnWork;
    property OnAbort: TNotifyEvent read FOnAbort write FOnAbort;
    property OnError : TNotifyEvent read FOnError write FOnError;
    property OnWorkEnd: TNotifyEvent read FOnWorkEnd write FOnWorkEnd;
    property OnWorkBegin: TOnWorkBegin read FOnWorkBegin write FOnWorkBegin;
    property KBBuffer: integer read FKBBuffer write SetKbBuffer default DEFAULT_KBBUFFER;
  end;

implementation

uses
  Windows;

type
  ALG_ID = ULONG;
  HCRYPTKEY = ULONG;
  HCRYPTHASH = ULONG;
  HCRYPTPROV = ULONG;
  LPAWSTR = PAnsiChar;
  PHCRYPTKEY = ^HCRYPTKEY;
  PHCRYPTPROV = ^HCRYPTPROV;
  PHCRYPTHASH = ^HCRYPTHASH;

const
  PROV_RSA_AES = 24;
  HP_HASHVAL = $0002;
  HP_HASHSIZE = $0004;
  CALG_MD5 = $00008003;
  CALG_MD4 = $00008002;
  CALG_SHA1  = $00008004;
  CALG_SHA_256 = $0000800c;
  CALG_SHA_384 = $0000800d;
  CALG_SHA_512 = $0000800e;
  CRYPT_NEWKEYSET = $00000008;

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 CryptGetHashParam(
    hHash: HCRYPTHASH;
    dwParam: DWORD;
    pbData: PBYTE;
    pdwDataLen: PDWORD;
    dwFlags: DWORD
  ): BOOL; stdcall;
  external ADVAPI32 name 'CryptGetHashParam';

function CryptDestroyHash(
    hHash: HCRYPTHASH
  ): BOOL; stdcall;
  external ADVAPI32 name 'CryptDestroyHash';

function CryptReleaseContext(
    hProv: HCRYPTPROV;
    dwFlags: DWORD
  ): BOOL; stdcall;
  external ADVAPI32 name 'CryptReleaseContext';

{ THashes }

constructor THashes.Create();
begin
  inherited Create();
  FAbort := false;
  FWorking := false;
  FKBBuffer := DEFAULT_KBBUFFER;
end;

procedure THashes.Abort();
begin
  FAbort := true;
  FWorking := false;
end;

procedure THashes.SetKBBuffer( value : integer );
begin
  if value <> FKBBuffer then
  begin
    if value >= 0 then
      FKBBuffer := value
    else
      FKBBuffer := DEFAULT_KBBUFFER;
  end;
end;

function THashes.CalcStringHash( str: string; algorithm : THashAlgorithm ) : string;
var
  stream : TStringStream;
begin
  FAbort := false;
  FWorking := true;
  result := EmptyStr;
  stream := TStringStream.Create( str );
  try
    result := CalcStreamHash( stream, algorithm );
  finally
    stream.Free();
  end;
end;

function THashes.CalcFileHash( filePath : string; algorithm : THashAlgorithm ) : string;
var
  stream : TFileStream;
begin
  FAbort := false;
  FWorking := true;
  result := EmptyStr;
  if FileExists( filePath ) then
  begin
    stream:= TFileStream.Create( filePath, fmOpenRead or fmShareDenyWrite );
    try
      result:= CalcStreamHash( stream, algorithm );
    finally
      stream.Free();
    end;
  end;
end;

{
  I get crazy with dinamyc array of byte, so I second the solution
  found at http://ktop.no-ip.org/topic.asp?TOPIC_ID=75388, that work
  like a charm.
}
function THashes.CalcStreamHash( stream: TStream; algorithm : THashAlgorithm ) : string;
var
  i: integer;
  hashLen : DWORD;
  bytesRead: DWORD;
  hashAlgId: ALG_ID;
  readBuffer: PByte;
  successQuery: BOOL;
  hashLenSize : DWORD;
  readPosition: int64;
  hProvider: HCRYPTPROV;
  hashAddress: HCRYPTHASH;
  hashDataPointer: ^ShortInt;
  hashBytesArray : array of Byte;
begin
  FAbort := false;
  FWorking := true;
  readPosition := 0;
  result:= EmptyStr;
  hashDataPointer := nil;
  hashLenSize := SizeOf( DWORD );

  successQuery := CryptAcquireContext( @hProvider, nil, nil, PROV_RSA_AES, 0 );

  if not successQuery then
  begin
    if GetLastError() = DWORD( NTE_BAD_KEYSET ) then
    begin
      successQuery := CryptAcquireContext
      (
        @hProvider,
        nil,
        nil,
        PROV_RSA_AES,
        CRYPT_NEWKEYSET
      );
    end;
  end;

  if successQuery then
  begin

    case algorithm of
      haMD5 : hashAlgId := CALG_MD5;
      haSHA1 : hashAlgId := CALG_SHA1;
      haSHA256 : hashAlgId := CALG_SHA_256;
      haSHA384 : hashAlgId := CALG_SHA_384;
      haSHA512 : hashAlgId := CALG_SHA_512;
    else
      raise EUknowAlgorithmException.Create( 'Unknow algorithm' );
    end;
    
    if CryptCreateHash( hProvider, hashAlgId, 0, 0, @hashAddress ) then
    begin
    
      if Assigned(FOnWorkBegin) then
        FOnWorkBegin(self, stream.Size);

      GetMem( readBuffer, FKBBuffer * 1024 );

      try
        if CryptGetHashParam( hashAddress, HP_HASHSIZE, @hashLen, @hashLenSize, 0 ) then
        begin
          GetMem( hashDataPointer, hashLen );
          
          while not FAbort do
          begin
            bytesRead := stream.Read( readBuffer^, FKBBuffer * 1024 );

            Inc( readPosition, bytesRead );

            if bytesRead = 0 then
            begin
              if CryptGetHashParam( hashAddress, HP_HASHVAL, PByte( hashDataPointer ), @hashLen, 0 ) then
              begin
              
                SetLength( hashBytesArray, hashLen );
                Move( hashDataPointer^, Pointer( hashBytesArray )^, hashLen );
                
                for i := 0 to hashLen - 1 do
                  result := result + LowerCase( IntToHex( Integer( hashBytesArray[ i ] ), 2 ) );
                  
                break;
              end;
            end;

            if not CryptHashData( hashAddress, readBuffer, bytesRead, 0 ) then
              break;

            if Assigned( FOnWork ) then
              FOnWork( Self, readPosition );
          end;

          if FAbort then
          begin
            if Assigned( FOnAbort )
              then FOnAbort( Self );
          end;

        end
        else
        begin
          if Assigned( FOnError ) then
            FOnError( self );
        end;
      finally
        FreeMem( readBuffer );
        FreeMem( hashDataPointer );
      end;
      
      CryptDestroyHash( hashAddress );
    end
    else
    begin
      if Assigned( FOnError ) then
        FOnError( self );
    end;

    CryptReleaseContext( hProvider, 0 );
  end
  else
  begin
    if Assigned( FOnError ) then
      FOnError( self );
  end;

  FWorking := false;
  
  if not FAbort and Assigned( FOnWorkEnd ) then
    FOnWorkEnd( self );
end;

end.

* Nota: Se incluyen las dos unidades porque creo que se pueden complementar, aunque, de hecho, pueden usarse por separado.
Responder Con Cita
  #17  
Antiguo 21-06-2012
Avatar de Casimiro Notevi
Casimiro Notevi Casimiro Notevi is offline
Moderador
 
Registrado: sep 2004
Ubicación: En algún lugar.
Posts: 32.039
Poder: 10
Casimiro Notevi Tiene un aura espectacularCasimiro Notevi Tiene un aura espectacular
Aunque yo también uso funciones sacadas del trabajo de seoane, me copio esta "personalización" tuya
Responder Con Cita
  #18  
Antiguo 21-06-2012
Avatar de mamcx
mamcx mamcx is offline
Moderador
 
Registrado: sep 2004
Ubicación: Medellín - Colombia
Posts: 3.911
Poder: 25
mamcx Tiene un aura espectacularmamcx Tiene un aura espectacularmamcx Tiene un aura espectacular
Un problema de copiar/pegar es que al inexperto le quedara muy dificil saber que parametros usar, que opciones y combinaciones.

SI no quieres quedar como un imbecil, lee antes de implementar CUALQUIER esquema/algoritmo de seguridad

http://codahale.com/how-to-safely-store-a-password/

http://stackoverflow.com/questions/1...ish-and-bcrypt


http://news.ycombinator.com/item?id=4125983

P.D: De buena gente les paso la respuesta correcta al dia de *hoy*. Igual es bueno leer sobre el tema.
__________________
El malabarista.
Responder Con Cita
  #19  
Antiguo 21-06-2012
Loviedo Loviedo is offline
Miembro
 
Registrado: dic 2004
Posts: 214
Poder: 0
Loviedo cantidad desconocida en este momento
El Sr. José Sagas se estará divirtiendo.
Saludos.
Responder Con Cita
  #20  
Antiguo 21-06-2012
Loviedo Loviedo is offline
Miembro
 
Registrado: dic 2004
Posts: 214
Poder: 0
Loviedo cantidad desconocida en este momento
Muchas veces no se pretende un código 'profesional', hay que tener en cuenta que muchos de los que leemos este foro somos auténticos novatos. Alucino con los conocimientos de personas como el Sr. Seoane, es muy dificil llegar a comprender sus códigos, el nivel es muy alto.
Estas funciones las copié de alguien que posiblemente esté a un nivel superior, pero a mi me funcionan bien.
Guardo la clave en un fichero .ini y la recupero de él.

Código Delphi [-]
function Encriptar(clave:string):string;
var
  i: byte;
  claverecep,clavesal: string;
begin
  claverecep := clave;
  for i := 1 to Length(claverecep) do
    clavesal := clavesal + CHR(255 - ord(claverecep[i]));
  result := clavesal;
end;

function DesEncriptar(clave:string):string;
var
  i: byte;
  claverecep,clavesal: string;
begin
  claverecep := clave;
  for i := 1 to Length(claverecep) do
    clavesal := clavesal + CHR(255-ord(claverecep[i]));
  result := clavesal;
end;

Saludos.
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

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Desencriptar Pin generado por PinPad marzelo Varios 1 02-09-2011 01:14:30
Cómo encriptar y desencriptar strings pockelsm3 Varios 7 25-06-2008 10:14:17
Uso del CAPICOM para Encriptar / Desencriptar moesis Noticias 0 28-08-2004 02:22:57
Encriptar y desencriptar datos en una tabla!!! DarkByte Conexión con bases de datos 2 20-11-2003 17:04:30


La franja horaria es GMT +2. Ahora son las 08:55:42.


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