How to iterate through each byte of an LPBYTE in C++

4.4k Views Asked by At

Excuse the simplicity of my question, I'm not used to working with Windows types.

I have an LPBYTE buffer and i wish to XOR each byte of it with another byte.

What is the proper way of getting the length of the buffer and iterating through it in C++? I'm trying to do something akin to:

LPBYTE buf = *something*;
char key = 'X';

for(int i=0;i<len(buf);i++)
    buf[i] = buf[i] ^ key;

Many Thanks!

2

There are 2 best solutions below

0
Matteo Italia On BEST ANSWER

buf is actually assign to the value of (LPBYTE) LockResource(LoadResource(NULL, hRsrc));, any guesses if that's null terminated?

Depends from the type of resource, but most probably no. Anyhow, since you are working with resources, you can get the resource size using the SizeofResource function.

Still, I'm not sure if you can write on stuff returned by LockResource (it actually returns a pointer to the region containing the resource, that is probably just a region in the memory-mapped executable). Most probably you'll want to copy it elsewhere before XORing it.

HGLOBAL resource=LoadResource(NULL, hRsrc);
if(resource==NULL)
{
    // ... handle the failure ...
}
LPBYTE resPtr=LockResource(resource);
DWORD resSize=SizeofResource(NULL, hRsrc);
if(resPtr==NULL || resSize==0)
{
    // ...
}
std::vector<BYTE> buffer(resPtr, resPtr+resSize);
// Now do whatever you want to do with your buffer
for(size_t i=0; i<buffer.size(); ++i)
    buffer[i]^=key;
0
AndersK On

A LPBYTE buffer in C(/C++) is just an address somewhere in memory, so you need to keep track of the length of that buffer preferably in an explicit way by having a size value.

E.g.

// use a struct instead to keep things together    
struct 
{
   LPBYTE buffer;
   size_t size;

} yourbuffer;

// init part
BYTE somewriteabledata[200];

yourbuffer.buffer = somewriteabledata;
yourbuffer.size = sizeof(somewriteabledata);

char key = 'X';

for(int i=0;i<yourbuffer.size;i++)
    yourbuffer.buf[i] = yourbuffer.buf[i] ^ key;