1. 程式人生 > >二進制文件每兩個的字節位置交換

二進制文件每兩個的字節位置交換

signed tle http files 模塊化 mit art 目的 input

(一).寫作緣由:

寫這篇博客的目的是是為了方便下次使用或者幫助其他需要的人。在打CTF的時候,偶爾會遇到還原一些文件,筆者遇到的是分析數據流量的時候,提取出了一個未知文件,用二進制編輯器打開,搜所文件頭,發現和某個文件頭有點相似,但是每兩個字節位置顛倒了,於是就想到把每兩個字節交換位置,就像下面這種:


技術分享圖片技術分享圖片


(二).演示及效果:

在命令行執行前後如下圖:

技術分享圖片技術分享圖片技術分享圖片



(三).貼上代碼:

代碼是C寫的,有點多不太美觀,功能太單一, 也沒弄啥模塊化,編寫環境是windows。

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

int main(int argc, const char** argv)
{
	//The pointer of input file and output file
	FILE *fin;
	FILE* fout;
	
	//The file name of input file and output
	char* inFile;
	char* outFile;

	//The pointer of single and double byte type
	unsigned short* pDouble = NULL;
	unsigned char* pSingle = NULL;

	//The memery buffer of header and tail pointer about input file
	void* fBuffStart = NULL;
	void* fBuffEnd = NULL;

	//The size of input file (Byte)
	unsigned long fileSize = 0;

	//Judge the count of parameter and the file name limit 
	if(argc != 3 || strlen(argv[1]) > 255 || strlen(argv[2]) > 255)
	{
		printf("\n[-]Usage: %s infile outfile\n", argv[0]);
		printf("[-]Filename limited: 255 Byte\n");
		exit(-1);
	}


	inFile = argv[1];
	outFile = argv[2];


	//Exception handling
	if(!(fin = fopen(inFile, "rb")))
	{
		printf("Error: open %s failed!\n", inFile);
		exit(-1);
	}


	//Obtain file size
	fseek(fin, 0, SEEK_END);
	fileSize = ftell(fin);
	fseek(fin, 0, SEEK_SET);

	//Alloc memery  for input file and read its data to memery
	fBuffStart = (unsigned char*)malloc(fileSize);
	memset(fBuffStart, 0, fileSize);
	fread(fBuffStart, 1, fileSize, fin);
	fclose(fin);


	//The position of start and end input file memery 
	fBuffEnd = (unsigned char*)fBuffStart + fileSize;
	pDouble = (unsigned short*)fBuffStart;

	//Exception handling
	if(!(fout = fopen(outFile,"wb")))
	{
		printf("Error: open %s failed!\n", outFile);
		exit(-1);
	}

	//Exchange position of each two byte
	while(pDouble != fBuffEnd)
	{
		pSingle = pDouble;
		fwrite(pSingle+1, 1, 1, fout);
		fwrite(pSingle, 1, 1, fout);
		pDouble++;
	}

	fclose(fout);

	return 0;
}


(四).若有不足之處,還請斧正。


二進制文件每兩個的字節位置交換