How to get the same MD5 with Delphi and PHP?

Whiler picture Whiler · Oct 5, 2012 · Viewed 9.3k times · Source

I'm using Delphi XE2 with FireMonkey.

I have read many other questions about MD5 but didn't find an answer to the issue I have... I've also tested different scripts to generate a MD5 from Delphi:

function MD5(const text: string) : string;
var
  md5 : TIdHashMessageDigest5;
begin
  md5    := TIdHashMessageDigest5.Create;
  Result := LowerCase(md5.HashStringAsHex(text, TEncoding.ANSI));
  md5.Free;
end;

or

function MD5(const text: String) : string;
var
  md5: IMD5;
begin
  md5:= GetMD5;
  md5.Init;
  md5.Update(TByteDynArray(RawByteString(AnsiString(text))), Length(AnsiString(text)));
  Result := LowerCase(md5.AsString);
end;

Both give me the same results... which is often the same I have within PHP:

$md5 = md5($toencode);
$md5 = hash("md5", $toencode);

But the results are different if I use Delphi or PHP, when I request the MD5 of one of these chars: " or ' There are maybe others chars which generate different results but I just find these ones during my tests...

I have tested with many extended ASCII characters and have the same MD5...

So, I don't understand why I have differences with few of them (" or ' ), and I'd like to know if there's a way to always generate the PHP MD5 result from Delphi, whatever the chars are.

Any idea?

For instance:

with Delphi:

": b15835f133ff2e27c7cb28117bfae8f4

': 3590cb8af0bbb9e78c343b52b93773c9

with PHP:

": 3bd864034f446da13581129bb17f9191

': 024c94d6e03b6f67a86b952b914816c7

Formalizing this question.. I've find the answer... BTW, I post it as others may have the same issue...

" and ' are escaped in PHP... so, within Delphi, I have to encode \" and \'... if you think I have forgotten chars or if you want to add some details, do not hesitate...

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Oct 5, 2012

Delphi is in the right here.

>>> hashlib.md5('"').hexdigest()
'b15835f133ff2e27c7cb28117bfae8f4'
>>> hashlib.md5("'").hexdigest()
'3590cb8af0bbb9e78c343b52b93773c9'

PHP should not need those characters escaped by default; make sure that it is configured to not do so.