1

My Goal: I am trying to encrypt .js files into .jse and decrypt only when it is running (obfuscate nodejs code).

var ffi = require('ffi');

//libpcrypt.so is a library to encrypt and decrypt files
var crypt = ffi.Library('./libpcrypt', {
  'decrypt' : [ 'string', ['string', 'string']]
});

require.extensions[".jse"] = function (module) {
   module.exports = (crypt.decrypt(module.filename, 'out'));
};

console.log(require('./routes.jse'));

I know, with cosole.log() source code can be printed out.

Problem: Decrypted code is a plain string, I am not able to convert it into a valid javascript object for exports. Is there a way to export the code string I decrypted?

rda3mon
  • 1,709
  • 4
  • 25
  • 37

2 Answers2

1

Here's your solution (not tested):

require.extensions['.jse'] = function(module, filename) {
  var content = crypt.decrypt(fs.readFileSync(filename), 'out')
  return module._compile(content, filename);
};

Happy debugging encrypted modules ;)

Anatoliy
  • 29,485
  • 5
  • 46
  • 45
  • Thanks. I saw this http://stackoverflow.com/a/9163557/458816 too. But I get `SyntaxError: Unexpected token ILLEGAL`. I thought it is encoding issue and converted to utf-8. but no use. – rda3mon Nov 05 '12 at 18:23
  • 1
    This code should work, because this code stolen from working library. Check your sources you are trying to _compile. – Anatoliy Nov 05 '12 at 18:26
  • I am still struggling with the error. Do you think it can be encoding issues? Any other suggestions?. – rda3mon Nov 05 '12 at 20:11
  • What do you see on `console.log(content);`? Expected source code? What if replace real code with some simple example like `module.exports = 2 + 2;` – Anatoliy Nov 05 '12 at 20:58
  • I see real code. And I tried as simple as `var x = 10`. Still same problem. – rda3mon Nov 05 '12 at 21:09
  • This is the correct solution. I had some other issues in .so. – rda3mon Nov 29 '12 at 23:32
0

module.exports is an object you can assign to (ie: module.exports.newFunc = someFunction;)

JSON.parse(crypt.decrypt(module.filename, 'out'));

EDIT So you should make your encrypted file a JSON class OR check out this answer to a similar question Load "Vanilla" Javascript Libraries into Node.js

Community
  • 1
  • 1
Louis Ricci
  • 20,804
  • 5
  • 48
  • 62
  • it didn't work. Because the string is plain and not JSON.stringify generated. Parse Error: `SyntaxError: Unexpected token e` – rda3mon Nov 05 '12 at 15:29
  • 2
    @mv945 - So you should make your encrypted file a JSON class OR check out this answer to a similar question http://stackoverflow.com/questions/5171213/load-vanilla-javascript-libraries-into-node-js – Louis Ricci Nov 05 '12 at 15:40
  • you pointed me right direction. thanks.. But I cannot accept your answer unless you edit it :) – rda3mon Nov 05 '12 at 16:01