JavaScript Ninja Techniques – JavaScript Based Obfuscation 101 Using Conversion Matrix Unify With A Prime Number

JavScript code obfuscation:
– is used for: “reasons”…
– provides some low-level protecting against: straight-forward debugging, hardening listening or program-flow.
– required to: execute fast, limit ‘eval’ execution, DOM friendly

in plain terms, JavaScript code obfuscation is a translatable matrix-conversion, that stills allows the D.O.M to “understand” the code, but makes debugging/watching too exhausting for a human.

best practices also covers minimal D.O.M evaluations: since obfuscated code usually executes few other methods for the same plain input, a good obfuscation algorithm adds fewest evaluated phrases as possible, and called ‘eval’ method only once.

here is a simple example, that uses JavaScript to obfuscated a plain JavaScript code (can be anything really…)

function fromE(n){
  var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890';
  var char;

  if(0 === n % 311) //311 is is a prime-number, it is not normally a multiplication of any ASCII char (maybe long UNICODE.. TODO: choose larger primer)
    char = String.fromCharCode(n / 311);
  else
    char = chars.substr(n,1);

  return char;
}

var phrase = 'console.log("hello")';
var obfuscated_phrase = "[" + phrase.replace(/./g,toE).replace(/\,$/,'') + "]";
var translated_plain_phrase = eval(obfuscated_phrase).join('');


console.log("From: \n" + phrase + "\n\n" + "To: \n" + obfuscated_phrase + "\n\n" + "Back To: \n" + translated_plain_phrase + "\n");

it result with the following output in the Console:

From: 
console.log("hello")

To: 
[fromE(2),fromE(14),fromE(13),fromE(18),fromE(14),fromE(11),fromE(4),fromE(14306),fromE(11),fromE(14),fromE(6),fromE(12440),fromE(10574),fromE(7),fromE(4),fromE(11),fromE(11),fromE(14),fromE(10574),fromE(12751)]

Back To: 
console.log("hello")


piping the result from this simple obfuscation matrix into Closure Compiler Service or UglifyJS may be interesting to witness, normally both c.compiler and uglifyJS try to “understand” the code by braking it to trees, then parse it using tree-logic permitted-operations resulting smaller trees, then re-parse the trees back to plain code,
so… it will either increase or decrease the complexity of the code using more or fewer transitions, rule-of-thumb is that you should obfuscate your code using three or more chained calls, this will result with a very deep and narrow tree, and UglifyJS or Google Closure-Compiler, will then “work for you” minifying and obfuscating the end-result even more, with minimal, or no-human intervention..