All pastes #440096 Raw Edit

Miscellany

public text v1 · immutable
·published 2007-04-14 19:46 UTC
rendered paste body
#include <iostream>
using namespace std;
#include <fstream>
#include <string>

template<class X>
inline string dec2hex(X intVal)		// Just a quick decimal-to-hexadecimal function
{
	string retString;
	do
	{
		int offset = intVal % 16;
		unsigned char theChar = (offset < 10 ? offset+48 : offset + 55);
		string tempString;
		tempString += theChar;
		retString = tempString + retString;
		intVal /= 16;
	} while(intVal);
	while(retString.length() % 2)	// Even length
	{
		retString = "0" + retString;
	}
	return retString;
}

int main(int argc, char* argv[])
{
	char* memFile = 0;
	size_t fileSize = 0;
	if(argc > 1)
	{
		ifstream inFile(argv[1], ios::in|ios::binary|ios::ate);
		if(!inFile)
		{
			cout << "Unable to open '" << argv[1] << "'" << endl;
			system("pause");
			return 0;
		}
		else
		{
			fileSize = inFile.tellg();
			memFile = new char[fileSize];
			inFile.seekg(0, ios::beg);
			inFile.read(memFile, fileSize);
			inFile.close();
		}
	}
	else
	{
		cout << "To use, drag&drop a DMB file onto this EXE." << endl;
		system("pause");
		return 0;
	}
	cout << "File successfully opened. Reading " << fileSize << " byte(s)." << endl;
	cout << "What string would you like to search for? ";
	string searchString;
	while(searchString.length()==0)
		getline(cin, searchString, '\n');	// input query
	
	bool found = false;
	size_t searchLen = searchString.length();
	size_t searchWidth = fileSize - searchLen + 1;
	
	for(size_t i=0; i<searchWidth; ++i)	// i is the initial offset for brute-forcing
	{
		unsigned char xorOffset = i & 0xFF;	// LSB
		bool match = true;
		for(size_t j=0; j<searchLen; ++j, xorOffset+=9)	// xorOffset increases by 9
		{
			// result = xorOffset ^ current byte
			unsigned char currChar = static_cast<unsigned char>(memFile[i+j]) ^ xorOffset;
			if(currChar != static_cast<unsigned char>(searchString[j]))
			{
				match = false;
				break;
			}
		}
		if(match)
		{
			found = true;
			cout << "Found at offset: " << i << "\t(0x" << dec2hex(i) << ")" << endl;
		}
	}
	if(!found)
		cout << "String not found." << endl;
	system("pause");
}