Tuesday, December 09, 2008

MD5 in Delphi

 
This is a lightweight implementation of the MD5 checksum algorithm in Delphi. It uses Windows' Crypto API.
 

You need the Crypto API headers for Delphi from http://jedi-apilib.sourceforge.net/ (Interface for Microsoft CryptoAPI version 2.0). Add Wcrypt2 to your uses clause. As the home page seems to have changed, you can now also get the file from http://stuff.irsoft.de/CryptoAPI2.zip.

 

function md5(const Input: String): String;
var
  hCryptProvider: HCRYPTPROV;
  hHash: HCRYPTHASH;
  bHash: array[0..$7f] of Byte;
  dwHashLen: DWORD;
  pbContent: PByte;
  i: Integer;
begin
  dwHashLen := 16;
  pbContent := Pointer(PChar(Input));

  Result := '';

  if CryptAcquireContext(@hCryptProvider, nil, nil, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT or CRYPT_MACHINE_KEYSET) then
  begin
    if CryptCreateHash(hCryptProvider, CALG_MD5, 0, 0, @hHash) then
    begin
      if CryptHashData(hHash, pbContent, Length(Input), 0) then
      begin
        if CryptGetHashParam(hHash, HP_HASHVAL, @bHash[0], @dwHashLen, 0) then
        begin
          for i := 0 to dwHashLen - 1 do
          begin
            Result := Result + Format('%.2x', [bHash[i]]);
          end;
        end;
      end;
      CryptDestroyHash(hHash);
    end;
    CryptReleaseContext(hCryptProvider, 0);
  end;

  Result := AnsiLowerCase(Result);
end;
Parsed in 0.024 seconds, using GeSHi © 2005 Nigel McNie

 

Example: md5('') returns d41d8cd98f00b204e9800998ecf8427e.

This doesn't work in Delphi 2009. It shouldn't be too hard to fix it though, just make sure the buffers are large enough for unicode strings and that the Crypt* functions are calling the *W and not the *A flavors.



Nikmati chatting lebih sering di blog dan situs web
Gunakan Wizard Pembuat Pingbox Online

0 Comments: