Question about Delphi 7 Chinese MD5

Use Indy's own md5 algorithm, the code is as follows:

uses IdHash, IdHashMessageDigest;

function GetStringMD5(const AInPut: string): string;
var
  MD5: TIdHashMessageDigest5;
{$IF CompilerVersion<20.0}
  Digest: T4x4LongWordRecord;
{$IFEND}
begin
  MD5 := TIdHashMessageDigest5.Create;
  try
{$IF CompilerVersion>20.0}   // Delphi 2009 +
    Result := LowerCase(MD5.HashStringAsHex(AInPut));
{$ELSE}
    Digest := MD5.HashValue(AInPut);
    Result := LowerCase(MD5.AsHex(Digest));
{$IFEND}
  finally
    MD5.Free;
  end;
end;

We found that this function is correct to deal with numbers and English. If it contains Chinese, the MD5 value will not match with other languages. In fact, the algorithm is no problem, it is a coding problem. Generally, MD5 uses UTF8 encoding. When using it, you need to convert the string to UTF8 encoding:

ShowMessage(GetStringMD5(UTF8Encode('中文')));

The MD5 value is: a7bac2239fcdcb3a067903d8077c4a07

If Delphi XE8 or later System.Hash.THashMD5, UTF8 conversion is not needed, the conversion has been done internally:

procedure THashMD5.Update(const Input: string);
begin
  Update(TEncoding.UTF8.GetBytes(Input));
end;

As long as this is enough:

ShowMessage(System.Hash.THashMD5.GetHashString('中文'));

 

Guess you like

Origin www.cnblogs.com/rtcmw/p/12678595.html