簡體   English   中英

C 通過二進制文件生成 header 文件

[英]C Generate a header file via a Binary file

我正在嘗試制作一種簡單的加密類型的東西。 所以我想做的是讀取可執行文件的內容,對其進行加密並生成一個 header 文件,該文件將包含一個帶有加密字節/二進制文件的變量,然后它將對其進行解密等等。所以問題是我如何將加密的東西導出到header 文件。 因為例如,如果您嘗試打印內容的字節表示,則可以使用

printf("%x", byte);

但我認為您不能使用這種格式將字節存儲在無符號字符中,因為通常的格式是

unsigned char bytes[] = {0x010, 0x038, 0x340 etc...}

在 Python 中我可以做到,但我似乎無法弄清楚如何直接在 C 中做到這一點。

如果您有來源推薦,請分享。

我目前正在嘗試專注於 Windows 可執行文件,很可能我會嘗試在虛擬分配的 Memory 上執行二進制代碼,我已經看到了一些可以做到的代碼,所以我想自己嘗試做。

快速而骯臟,不安全且未經測試。 讀取INPUT_FILE中定義的文件,輸出到OUTPUT_FILE,格式為: unsigned char var[] = { 0xXX, 0xXX... }; 變量的名稱由 VARIABLE_NAME 控制。 您應該添加自己的健全性檢查,即檢查 fopen() 等的返回值。

#include <stdio.h>
#include <stdlib.h>

#define INPUT_FILE "file.exe"
#define OUTPUT_FILE "out.txt"
#define VARIABLE_NAME "bytes"

int main(int argc, char *argv[]) {
    FILE *fp = fopen(INPUT_FILE, "rb");

    // Get file size
    fseek(fp, 0, SEEK_END);
    long size = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    // Alloc, read
    unsigned char *buf = malloc(size);
    fread(buf, size, 1, fp);
    fclose(fp);

    // Write the data out
    fp = fopen(OUTPUT_FILE, "wb");
    fprintf(fp, "unsigned char %s[] = { ", VARIABLE_NAME);
    for (long i = 0; i < size; i++) {
        fprintf(fp, "0x%02x%s", buf[i], (i == size-1) ? " };" : ", ");
    }
    fclose(fp);
    free(buf);
    return 0;
}

你想要這樣的東西:

#include <stdio.h>

int encode(int c)
{
  return (unsigned char) (c ^ 0xf);
}

int main(int argc, char ** argv)
{
  if (argc != 3) {
    fprintf(stderr, "usage: %s <file in> <file out>\n", *argv);
  }
  else {
    FILE * fpin;
    FILE * fpout;
    
    if ((fpin = fopen(argv[1], "rb")) == NULL) /* under Windows 'b' is necessary to read binary */
      perror("cannot open inpout file");
    else if ((fpout = fopen(argv[2], "w")) == NULL)
      perror("cannot open inpout file");
    else {
      const char * sep = "unsigned char bytes[] = {";
      int c;
     
      while ((c = fgetc(fpin)) != EOF) {
        fprintf(fpout, "%s0x%x", sep, encode(c));
        sep = ", ";
      }
      
      fputs("};\n", fpout);
      fclose(fpin);
      fclose(fpout);
    }
  }
  
  return 0;
}

當然修改編碼

編譯和執行:

pi@raspberrypi:/tmp $ gcc -Wall e.c
pi@raspberrypi:/tmp $ ./a.out ./a.out h
pi@raspberrypi:/tmp $ cat h
unsigned char bytes[] = {0x70, 0x4a, 0x43, 0x49, 0xe, 0xe, 0xe, 0xf ... 0xf, 0xf, 0xf, 0xf, 0xf};
pi@raspberrypi:/tmp $ ls -l h
-rw-r--r-- 1 pi pi 43677 juil.  4 18:44 h

(我削減cat h結果只顯示它的開始和結束)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM