Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <vector>
- #include <algorithm>
- // Function to read the content of the file into a vector
- std::vector<uint8_t> readBinaryFile(const std::string& filename) {
- std::ifstream file(filename, std::ios::binary | std::ios::ate);
- if (!file.is_open()) {
- throw std::runtime_error("Failed to open file");
- }
- std::streamsize fileSize = file.tellg();
- file.seekg(0, std::ios::beg);
- std::vector<uint8_t> buffer(fileSize);
- if (!file.read(reinterpret_cast<char*>(buffer.data()), fileSize)) {
- throw std::runtime_error("Failed to read file");
- }
- return buffer;
- }
- // Function to modify the bytes in the vector using a mask
- void modifyBytes(std::vector<uint8_t>& data, const std::vector<uint8_t>& pattern, const std::vector<uint8_t>& mask, const std::vector<uint8_t>& replacement) {
- if (pattern.size() != mask.size() || pattern.size() != replacement.size()) {
- throw std::runtime_error("Pattern, mask, and replacement must have the same size");
- }
- auto it = std::search(data.begin(), data.end(), pattern.begin(), pattern.end());
- while (it != data.end()) {
- auto startPos = std::distance(data.begin(), it);
- // Check if the pattern matches using the mask
- bool patternMatches = true;
- for (size_t i = 0; i < pattern.size(); ++i) {
- if ((data[startPos + i] & mask[i]) != pattern[i]) {
- patternMatches = false;
- break;
- }
- }
- // If the pattern matches, replace the bytes
- if (patternMatches) {
- std::copy(replacement.begin(), replacement.end(), data.begin() + startPos);
- }
- it = std::search(it + 1, data.end(), pattern.begin(), pattern.end());
- }
- }
- int main() {
- try {
- std::string filename = "example.exe";
- std::vector<uint8_t> fileData = readBinaryFile(filename);
- // Define the pattern, mask, and replacement
- std::vector<uint8_t> pattern = {0x12, 0x34, 0x56};
- std::vector<uint8_t> mask = {0xFF, 0xFF, 0xFF}; // Use 0xFF for exact match, 0x00 to ignore the byte
- std::vector<uint8_t> replacement = {0xAB, 0xCD, 0xEF};
- modifyBytes(fileData, pattern, mask, replacement);
- // Write the modified data back to the file (optional)
- std::ofstream outputFile(filename, std::ios::binary);
- if (!outputFile.write(reinterpret_cast<const char*>(fileData.data()), fileData.size())) {
- throw std::runtime_error("Failed to write to file");
- }
- std::cout << "Modification successful.\n";
- }
- catch (const std::exception& ex) {
- std::cerr << "Error: " << ex.what() << std::endl;
- return 1;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement