开发者

Delphi: crypting resource file

I have this function that should crypt bytes from resource file but it's just crashing my app:

function crypt(src: Pointer; le开发者_如何转开发n: DWORD): DWORD;
var
  B: TByteArray absolute src;
  index: DWORD;
begin
  for index := 0 to len - 1 do
  begin
    B[index] := B[index] xor 5; //just to test if its working
  end;
  result := 1;
end;

i am using it like this:

hFind := FindResource(...);
size := SizeOfResource(HInstance, hFind);
hRes :=LoadResource(HInstance, hFind);
bytes :=LockResource(hRes);
crypt(bytes, size);

if i dont call the crypt function program works. What am i doing wrong?


You've got two problems with that code. First is with the byte array, its elements do not contain your resource data but random data starting with the address of your pointer 'src'. Use a pointer to a TByteArray like this:

var
  B: PByteArray absolute src;              
  index: DWORD;
begin
  for index := 0 to len - 1 do
  begin
    B^[index] := B^[index] xor 5; //just to test if its working
  end;
  ..


Second is, you'll still get an AV for trying to modify a read-only memory segment. Depending on what you are trying to do, you can use VirtualProtect on 'bytes' before calling 'crypt', or copy the memory to a byte array and modify it there, or use BeginUpdateResource-UpdateResource-EndUpdateResource if you're trying to modify the resource.


Code like this is easiest to write with pointers like this:

function crypt(src: Pointer; len: DWORD): DWORD;
var
  B: ^Byte;
  index: DWORD;
begin
  B := src;
  for index := 0 to len - 1 do
  begin
    B^ := B^ xor 5; //just to test if its working
    inc(B);
  end;
  result := 1;
end;

Naturally you do need to respect the issue of read-only memory that Sertac highlighted. I'm just adding this code to illustrate what I believe to be the canonical way to walk a buffer that arrives as a void pointer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜