Skip to content

Instantly share code, notes, and snippets.

@LuviKunG
Created May 13, 2024 01:41
Show Gist options
  • Save LuviKunG/f2cb6f769fc5abd23b6788c6ea8fd719 to your computer and use it in GitHub Desktop.
Save LuviKunG/f2cb6f769fc5abd23b6788c6ea8fd719 to your computer and use it in GitHub Desktop.
Simple obfuscator.
namespace LuviKunG
{
static class Obfuscator
{
/// <summary>
/// Obfuscate string with key.
/// </summary>
/// <param name="key">Key to obfuscate.</param>
/// <param name="str">String to obfuscate.</param>
/// <returns>Obfuscated byte array.</returns>
public static byte[] Obfuscate(in byte[] key, string str)
{
byte[] buffer = Encoding.UTF8.GetBytes(str);
return ShiftByte(key, buffer);
}
/// <summary>
/// Obfuscate struct with key.
/// </summary>
/// <typeparam name="T">Type of struct.</typeparam>
/// <param name="key">Key to obfuscate.</param>
/// <param name="obj">struct to obfuscate.</param>
/// <returns>Obfuscated byte array.</returns>
public static byte[] Obfuscate<T>(in byte[] key, T obj) where T : struct
{
int size = Marshal.SizeOf(obj);
byte[] buffer = new byte[size];
IntPtr p = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(obj, p, false);
Marshal.Copy(p, buffer, 0, size);
buffer = ShiftByte(key, buffer);
}
finally
{
Marshal.FreeHGlobal(p);
}
return buffer;
}
/// <summary>
/// Deobfuscate byte array with key to string.
/// </summary>
/// <param name="key">Key to deobfuscate.</param>
/// <param name="data">Obfuscated byte array.</param>
/// <returns>Deobfuscated string.</returns>
public static string Deobfuscate(in byte[] key, byte[] data)
{
byte[] buffer = ShiftByte(key, data);
return Encoding.UTF8.GetString(buffer);
}
/// <summary>
/// Deobfuscate byte array with key to struct.
/// </summary>
/// <typeparam name="T">Type of struct.</typeparam>
/// <param name="key">Key to deobfuscate.</param>
/// <param name="data">Obfuscated byte array.</param>
/// <returns>Deobfuscated struct.</returns>
public static T Deobfuscate<T>(in byte[] key, byte[] data) where T : struct
{
int size = Marshal.SizeOf(typeof(T));
IntPtr p = Marshal.AllocHGlobal(size);
try
{
byte[] buffer = ShiftByte(key, data);
Marshal.Copy(data, 0, p, size);
object? o = Marshal.PtrToStructure(p, typeof(T));
return (T)o!;
}
finally
{
Marshal.FreeHGlobal(p);
}
}
/// <summary>
/// Shift byte array.
/// </summary>
/// <param name="key">Key to shift.</param>
/// <param name="data">Data to shift.</param>
/// <returns>Sifted byte array.</returns>
private static byte[] ShiftByte(in byte[] key, byte[] data)
{
byte[] obf = new byte[data.Length];
for (int i = 0; i < data.Length; i++)
{
obf[i] = (byte)(data[i] ^ key[i % key.Length]);
}
return obf;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment