Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   encriptar y desencriptar (https://www.clubdelphi.com/foros/showthread.php?t=79262)

JoseSagas 19-06-2012 22:26:22

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

Casimiro Notevi 19-06-2012 22:47:18

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.

Delphius 19-06-2012 23:02:45

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. :D

Creo que lo que has intentado decir es cifrar y descifrar ;)

Saludos,

duilioisola 20-06-2012 10:07:39

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'

cecam 20-06-2012 10:29:13

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!

newtron 20-06-2012 10:42:29

Cita:

Empezado por cecam (Mensaje 435621)

Menos mal que hay alguien serio en este foro. :p

Northern 20-06-2012 11:05:55

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.

Casimiro Notevi 20-06-2012 13:12:37

Sin embargo, sí viene criptografía.

Loviedo 20-06-2012 13:21:04

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.

Casimiro Notevi 20-06-2012 13:45:43

¿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.
:)

mamcx 20-06-2012 19:01:42

Cita:

Empezado por cecam (Mensaje 435621)

Usar MD5 para encriptar ya esta desacreditado.

duilioisola 20-06-2012 19:17:18

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

mamcx 20-06-2012 20:07:01

Es correcto. MD5 es para hash, no encriptar.

Una exelente introduccion al tema:

http://coding.smashingmagazine.com/2...phy-made-easy/

JoseSagas 20-06-2012 20:16:30

muchas gracias a todos por su ayuda, me ayudaron mucho :)

Delphius 20-06-2012 21:00:21

Cita:

Empezado por Loviedo (Mensaje 435634)
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,

dec 20-06-2012 23:47:11

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.

Casimiro Notevi 21-06-2012 00:00:18

Aunque yo también uso funciones sacadas del trabajo de seoane, me copio esta "personalización" tuya :)

mamcx 21-06-2012 00:28:53

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.

Loviedo 21-06-2012 00:51:50

El Sr. José Sagas se estará divirtiendo.
Saludos.

Loviedo 21-06-2012 01:25:58

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.


La franja horaria es GMT +2. Ahora son las 22:10:21.

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