justme_
justme_

Reputation: 665

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; len: 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?

Upvotes: 0

Views: 871

Answers (2)

David Heffernan
David Heffernan

Reputation: 612954

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.

Upvotes: 0

Sertac Akyuz
Sertac Akyuz

Reputation: 54802

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.

Upvotes: 4

Related Questions