Delphi在二进制文件头部加数据或删除数据

今天想要在一个二进制文件头部加上一个特殊标志,在后续处理时又需要把该标志先移除。在网上搜了很久,没有很好的解决办法,最后想了个办法,用一个临时Stream来处理。上代码:

 

const
   EncFileHeader = '1234567890';  //特殊标志

function EncryptFile(inFile, outFile: PChar; password: PChar): Boolean; stdcall;
var
  output: TFileStream;
  input: TFileStream;
  AES: TAESFull;
  bFlag: Boolean;
  keySize: integer;
  Pass: String;
  Digest: TSHA256Digest;
  ret: Integer;
  tmpStream: TMemoryStream;
begin

  Pass := Password;
  SHA256Weak(Pass, Digest);

  Result := True;
  if inFile = outFile then
  begin
    Result := False;
    Exit;
  end;
  bFlag := True;

  keySize := sizeof(Digest)*8;
  if keySize <128 then keySize := 128;

  tmpStream := TMemoryStream.Create;
  try
    input := TFileStream.Create (inFile, fmOpenRead);
    output := TFileStream.Create (outFile, fmCreate);
    ret := AES.EncodeDecode (Digest, keySize, input.Size, bFlag, input, output, nil, nil);

    //往输出文件头中写入特殊标志
    output.Seek(0, soFromBeginning);
    tmpStream.Write(EncFileHeader, length(EncFileHeader));
    tmpStream.CopyFrom(output, output.Size);
    output.Free;
    output := TFileStream.Create (outFile, fmCreate);
    tmpStream.Seek(0, soFromBeginning);
    output.CopyFrom(tmpStream, tmpStream.Size);
    //写入特殊标志结束

    if ret<>0 then Result := False;
  finally
    input.Free;
    output.Free;
    tmpStream.Free;
  end;
end;
function EncFile(inFile, outFile: PChar): Boolean; stdcall;
begin
  Result := EncryptFile(inFile, outFile, PChar(GetEK()));
end;

function DecryptFile(inFile, outFile: PChar; password: PChar): Boolean; stdcall;
var
  output: TFileStream;
  input: TFileStream;
  tmpStream: TStringStream;
  AES: TAESFull;
  bFlag: Boolean;
  keySize: integer;
  Pass: String;
  Digest: TSHA256Digest;
  ii, ret: Integer;
  Buffer: array of byte;
  sTmp: String;
begin

  Pass := Password;
  SHA256Weak(Pass, Digest);

  Result := True;
  if inFile = outFile then
  begin
    Result := False;
    Exit;
  end;
  bFlag := False;

  keySize := sizeof(Digest)*8;
  if keySize <128 then keySize := 128;

  SetLength(Buffer, Length(EncFileHeader));
  try
    input := TFileStream.Create (inFile, fmOpenRead);
    output := TFileStream.Create (outFile, fmCreate);

    //把文件头上特殊标志移除(跳过)
    tmpStream := TStringStream.Create('');
    if input.Size > Length(EncFileHeader) then
    begin
      tmpStream.CopyFrom(input, Length(EncFileHeader));
      if tmpStream.DataString <> EncFileHeader then
      begin
        //当文件头部信息与特殊标志不相符时,认为没有特殊标志,则把指针指回到0,让后续代码从头开始处理流;
     //否则,后续代码从当前位置开始处理,即跳过了特殊标志
        tmpStream.Seek(0, soFromBeginning); 
      end;
    end;

    ret := AES.EncodeDecode (Digest, keySize, input.Size, bFlag, input, output, nil, nil);
    if ret<>0 then Result := False;
  finally
    input.Free;
    output.Free;
    tmpStream.Free;
  end;
end;

 

你可能感兴趣的:(T_L_Delphi)