xor each byte with 0x71

蹲街弑〆低调 提交于 2021-02-18 06:35:10

问题


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?


回答1:


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.




回答2:


Try this:

my_num = int(f.read(1))

And then xor the number stored in my_num.



来源:https://stackoverflow.com/questions/5037762/xor-each-byte-with-0x71

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!