C实现修改可执行文件中的字符串,生成新的可执行文件

jopen 10年前

这种技术常用在远程控制软件中,我们已有远程控制软件的服务器端。我们利用远程控制软件的客户端配置生成我们自己的服务端软件,实现服务器端的端口及IP地址更新的功能。

 

下边看源代码

 

#include <stdio.h>  #include <Windows.h>          int FindStr(char *destStr, char *srcStr, int destStrLen, int srcStrLen);  void ReplaceStr(char *destStr, char * srcStr, int beginPoint);      int main()  {  FILE *pReadFile;  FILE *pOutFile;  char *pFileBuf;      //打开我们要修改的源程序  if ((pReadFile = fopen("../custom/TestPE.exe", "rb")) == NULL)  {  printf("It's failure to open the readable file\n");  return -1;  }      //我们要生成的源程序  if ((pOutFile = fopen("../custom/TestPE1.exe", "wb")) == NULL)  {  printf("It's failure to open the writable file\n");  return -1;  }      fseek(pReadFile, 0L, SEEK_END);  int fileLen = ftell(pReadFile);      pFileBuf = (char *)malloc(fileLen + 1);  if (pFileBuf == NULL)  {  fclose(pReadFile);  return -1;  }      fseek(pReadFile,0L,SEEK_SET);  fread(pFileBuf, fileLen, sizeof(char), pReadFile);  pFileBuf[fileLen] = '\0';      //我们要修改成的字符串  char *modifyStr = "BBBBBBBBB";  //源程序中的字符串  char *findStr = "AAAAAAAAAAAAAAA";  int beginPoint;      //我们在读取的源程序数组中查找我们要查找的字符串的起始位置  beginPoint = FindStr(pFileBuf, findStr, fileLen, 0);  if (beginPoint == -1)  {  printf("It's failure to find the string\n");  return -1;  }      //替换我们的字符串  ReplaceStr(pFileBuf, modifyStr, beginPoint);      //生成我们修改后的源程序  fwrite(pFileBuf, fileLen, sizeof(char), pOutFile);      fclose(pReadFile);  fclose(pOutFile);  if (pFileBuf != NULL)  {  free(pFileBuf);  pFileBuf = NULL;  }      return 0;  }      int FindStr(char *destStr, char *srcStr, int destStrLen, int srcStrLen)  {  int i,j,findStrLen;      if (srcStrLen == 0)  {  findStrLen = strlen(srcStr);  }  else  {  findStrLen = srcStrLen;  }      for (i = 0; i < destStrLen; i++)  {  for (j = 0; j < findStrLen; j++)  {  if (destStr[i + j] != srcStr[j])  {  break;  }  }      if (j == findStrLen)  {  return i;  }  }  return -1;  }      void ReplaceStr(char *destStr, char *srcStr, int beginPoint)  {  int srcStrLen, i;  srcStrLen = strlen(srcStr);      for (i = 0; i < srcStrLen; i++)  {  destStr[beginPoint + i] = srcStr[i];  }      destStr[beginPoint + srcStrLen] = '\0';  }
来自:http://blog.csdn.net/u012554768/article/details/39396117