Forum Discussion

aleksandr_tsura's avatar
aleksandr_tsura
Occasional Contributor
11 years ago

MD5 Hash

Hi, If there is away to test md5 hashed password with delphi script in TestComplete. /Aleksandr
  • HKosova's avatar
    11 years ago

    Hi Alexandr,

    DelphiScript doesn't have built-in functions for calculating the MD5 hash, but you can use the .NET System.Security.Cryptography.MD5 class for this. Here's an example:

     

    function getMD5Hash(str); forward;
    procedure Test;
    var strPassword, strHashFromApp, strHashExpected;
    begin
      strPassword := 'test';
      strHashFromApp := '098F6BCD4621D373CADE4E832627B4F6'; // the hash to test
      strHashExpected := getMD5Hash(strPassword);

    if aqString.Compare(strHashFromApp, strHashExpected, false) = 0 then
        Log.Checkpoint(
          'The password''s MD5 hash is correct.',
          'Password: ' + strPassword + #13#10 +
          'MD5 Hash: ' + strHashExpected
        )
    else
        Log.Error(
          'The password''s MD5 hash is incorrect.',
          'Password: ' + strPassword + #13#10 +
          'MD5 hash (expected): ' + strHashExpected + #13#10 +
          'MD5 hash (tested value): ' + strHashFromApp
        );
    end;


    // Returns an MD5 hash of the specified string
    function getMD5Hash(str);
    var md5, inputBytes, hashBytes, hashStr;
    begin
      // Get the MD5 hash as a byte array
      md5 := dotNET.System_Security_Cryptography.MD5.Create_3;
      inputBytes := dotNET.System_Text.Encoding.ASCII.GetBytes_2(str); // Replace ASCII with UTF8 if the string is in UTF-8
      hashBytes := md5.ComputeHash(inputBytes);

      // Convert the byte array to a hex string
      hashStr := dotNET.System.BitConverter.ToString(hashBytes).OleValue;
      hashStr := aqString.Replace(hashStr, '-', '');
      Result := hashStr;
    end;