user277465
user277465

Reputation:

xor each byte with 0x71

I needed to read a byte from the file, xor it with 0x71 and write it back to another file. However, when i use the following, it just reads the byte as a string, so xoring creates problems.

f = open('a.out', 'r')
f.read(1)

So I ended up doing the same in C.

#include <stdio.h>
int main() {
  char buffer[1] = {0};
  FILE *fp = fopen("blah", "rb");
  FILE *gp = fopen("a.out", "wb");
  if(fp==NULL) printf("ERROR OPENING FILE\n");
  int rc;
  while((rc = fgetc(fp))!=EOF) {
    printf("%x", rc ^ 0x71);
    fputc(rc ^ 0x71, gp);
  }
  return 0;
}

Could someone tell me how I could convert the string I get on using f.read() over to a hex value so that I could xor it with 0x71 and subsequently write it over to a file?

Upvotes: 7

Views: 29738

Answers (2)

Scott Griffiths
Scott Griffiths

Reputation: 21925

If you want to treat something as an array of bytes, then usually you want a bytearray as it behaves as a mutable array of bytes:

b = bytearray(open('a.out', 'rb').read())
for i in range(len(b)):
    b[i] ^= 0x71
open('b.out', 'wb').write(b)

Indexing a byte array returns an integer between 0x00 and 0xff, and modifying in place avoid the need to create a list and join everything up again. Note also that the file was opened as binary ('rb') - in your example you use 'r' which isn't a good idea.

Upvotes: 18

bstamour
bstamour

Reputation: 7766

Try this:

my_num = int(f.read(1))

And then xor the number stored in my_num.

Upvotes: -2

Related Questions