0

I need to mangle (obfuscate) JavaScript strings using hexadecimal encoding.

Source code:

var a = 'a';

Mangled code:

var a = '\x61';

It is easy to convert string to a hexadecimal value:

var map = {
    '\b': '\\b',
    '\f': '\\f',
    '\n': '\\n',
    '\r': '\\r',
    '\t': '\\t',
};

var hex = function (str) {
    var result = '';
    for (var i = 0, l = str.length; i < l; i++) {
        var char = str[i];
        if (map[char]) {
            result += map[char];
        } else if ('\\' == char) {
            result += '\\' + str[++i];
        } else {
            result += '\\x' + str.charCodeAt(i).toString(16);
        }
    }
    return result;
};

But when I add this string to the output file I get:

var a = '\\x61';

P.S. I use esprima/escodegen/estraverse to work with AST.

alpha
  • 65
  • 8

1 Answers1

2

Below is an draft of implementation based on Качалов Тимофей's solution:

var esprima = require('esprima');
var estraverse = require('estraverse');
var escodegen = require('escodegen');

function stringToUnicode(string) {
    return '"' + string.replace(/[\s\S]/g, function (escape) {
       return '\\u' + ('0000' + escape.charCodeAt().toString(16)).slice(-4);
    }) + '"';
}

var tree = esprima.parse(code);
//...
estraverse.replace(tree, {
    leave: function(node){
        if (node.type === 'Literal' && (node.raw[0] === '"' || node.raw[0] === '\'' )){
            node['x-verbatim-property'] = {
                content : stringToUnicode(node.value),
                precedence: escodegen.Precedence.Primary
            };
        }
    }
});
//...
var result = escodegen.generate(tree, {verbatim: 'x-verbatim-property'});    
Community
  • 1
  • 1
alpha
  • 65
  • 8