Delphi - Reading a file signature and compare them

时间:2015-04-29 00:25:13

标签: delphi hex digital-signature

I need of a little help in delphi. I have search in very places but i can't find the answer for my question.

How i can read a file signature(4 bytes in my case) and put the value in HEX into a string? The signature my program will have to identify is $4E4553A1.

I need to test if the file, for example. C:\Happy.bin. Have this signature. To avoid people to put wrong format files in my software. Signature are the first 4 bytes in it.

Thank you so much, english isn't my first language, so sorry for the mistakes. Love you all

1 个答案:

答案 0 :(得分:1)

这可能是最简单的。你调用它并传入文件名。

function CheckSignature(aFilename: string): Boolean;
var
  signature: UInt32;
  myFile: TFileStream;
begin
  myFile := TFileStream.Create(aFilename, fmOpenRead or fmShareDenyWrite);
  try
    if myFile.Read(signature, SizeOf(signature)) = SizeOf(signature) then
      Result := (signature = $A153454E)
    else
      Result := False;
  finally
    myFile.Free;
  end;
end;

由于整数存储数据的方式(小端),签名反转。

要使用此功能,您可以这样称呼它:

begin
  if CheckSignature('C:\Happy.bin') then
    ShowMessage('Matched')
  else
    ShowMessage('Didn''t match');
end;