Jan 18, 2018

Obfuscate a String

The following code explains how to obfuscate and deobfuscate a Base64 encoded string by using a XOR in the string.

public class Test
{
    /// <summary>
    /// Constant for Obfuscating Base64 encoded text
    /// </summary>
    const byte xorConstant = 0x53;

    /// <summary>
    /// Obfuscates string by Base64 encoding using constant "xorConstant"
    /// </summary>
    /// <param name="text">String to encode</param>
    /// <returns>Base64 encoded obfuscated string</returns>
    public static string Obfuscate(string text)
    {
        if (string.IsNullOrEmpty(text))
        {
            return null;
        }
        else
        {
            byte[] data = Encoding.UTF8.GetBytes(text);
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)(data[i] ^ xorConstant);
            }
            return Convert.ToBase64String(data);
        }
    }

    /// <summary>
    /// Deobfuscates string by Base64 decoding using constant "xorConstant"
    /// </summary>
    /// <param name="text">String to decode</param>
    /// <returns>Original string</returns>
    public static string DeObfuscate(string text)
    {
        if (string.IsNullOrEmpty(text))
        {
            return null;
        }
        else
        {
            byte[] data = Convert.FromBase64String(text);
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)(data[i] ^ xorConstant);
            }
            return Encoding.UTF8.GetString(data);
        }
    }
}

No comments: