Scalabium Software

SMReport Autogenerated
Knowledge for your independence'.
Home Delphi and C++Builder tips


#173: How can I calculate the hash for string (CryptAPI)?

today I want to continue the serie of tips for Crypt API in Delphi.
I'll show the code to calculate the MD5 hash for any string. You may easy to modify the code to calculate the hash for file/any stream or use SHA-algorithm (or any other) instead MD5.

function MD5(const Value: string): string;
var
  hCryptProvider: HCRYPTPROV;
  hHash: HCRYPTHASH;
  bHash: array[0..$7F] of Byte;
  dwHashLen: dWord;
  i: Integer;
begin
  dwHashLen := 16;
  if (Value = '') then
  begin
    Result := 'd41d8cd98f00b204e9800998ecf8427e';
    exit;
  end
  else
    Result := '';

  {get context for crypt default provider}
  if CryptAcquireContext(@hCryptProvider, nil, nil, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT or CRYPT_MACHINE_KEYSET) then
  begin
    {create hash-object MD5}
    if CryptCreateHash(hCryptProvider, CALG_MD5, 0, 0, @hHash) then
    begin
      {get hash from password}
      if CryptHashData(hHash, @Value[1], Length(Value), 0) then
      begin
        if CryptGetHashParam(hHash, HP_HASHVAL, @bHash[0], @dwHashLen, 0) then
        begin
          for i := 0 to dwHashLen-1 do
            Result := Result + IntToHex(bHash[i], 2);
        end;
      end;
      {destroy hash-object}
      CryptDestroyHash(hHash);
    end;
    {release the context for crypt default provider}
    CryptReleaseContext(hCryptProvider, 0);
  end;

  Result := AnsiLowerCase(Result);
end;

For SHA algorithm use the CALG_SHA instead CALG_MD5.
For this code you need the Crypt API headers too (same as in my previous tip)


Published: April 3, 2007

See also
 
SMExport suite
Paradox to Text converter
DBExport tools
Paradox to MS Access converter
Clarion to Text converter
Clarion Viewer
ABA Database Convert
Metafile Convert
Excel Web-stream
Word Web-stream
 
 


Contact to webmaster

 

Borland Software Code Gear Scalabium Delphi tips

Copyright© 1998-2024, Scalabium Software. All rights reserved.
webmaster@scalabium.com

SMReport Autogenerated