forked from jjxtra/HexAndReplace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHexAndReplaceApp.cs
83 lines (78 loc) · 2.83 KB
/
HexAndReplaceApp.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace HexAndReplace
{
/// <summary>
/// App
/// </summary>
public static class HexAndReplaceApp
{
/// <summary>
/// Main
/// </summary>
/// <param name="args">Args</param>
public static int Main(string[] args)
{
bool matchFound = false;
if (args.Length < 3)
{
Console.WriteLine("Replace first instance of one hex sequence with another. Usage: <File Name> <Find Hex> <Replacement Hex>.");
return -1;
}
byte[] find = ConvertHexStringToByteArray(Regex.Replace(args[1], "0x|[ ,]", string.Empty).Normalize().Trim());
byte[] replace = ConvertHexStringToByteArray(Regex.Replace(args[2], "0x|[ ,]", string.Empty).Normalize().Trim());
if (find.Length != replace.Length)
{
throw new ArgumentException("Find and replace hex must be same length");
}
byte[] bytes = File.ReadAllBytes(args[0]);
foreach (int index in PatternAt(bytes, find))
{
for (int i = index, replaceIndex = 0; i < bytes.Length && replaceIndex < replace.Length; i++, replaceIndex++)
{
bytes[i] = replace[replaceIndex];
}
Console.WriteLine("Pattern found at offset {0} and replaced.", index);
matchFound = true;
}
if (matchFound)
{
File.WriteAllBytes(args[0], bytes);
return 0;
}
else
{
Console.WriteLine("Pattern not found");
return -1;
}
}
private static IEnumerable<int> PatternAt(byte[] source, byte[] pattern)
{
for (int i = 0; i < source.Length; i++)
{
if (source.Skip(i).Take(pattern.Length).SequenceEqual(pattern))
{
yield return i;
}
}
}
private static byte[] ConvertHexStringToByteArray(string hexString)
{
if (hexString.Length % 2 != 0)
{
throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));
}
byte[] data = new byte[hexString.Length / 2];
for (int index = 0; index < data.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
data[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return data;
}
}
}