Writing simple obfuscation and minification system (2024)

Writing simple obfuscation and minification system (1)

Himanshu Mishra

Posted on

Writing simple obfuscation and minification system (3) Writing simple obfuscation and minification system (4) Writing simple obfuscation and minification system (5) Writing simple obfuscation and minification system (6) Writing simple obfuscation and minification system (7)

#node #obfuscate #javascript #security

Obfuscation is the process of making your code unclear and unreadable to humans. This adds a level of security to source code specially in web world were source code is readily available. Minification is the process of removing unnecessary data present in code resulting in smaller file sizes and faster loading. In this tutorial we will focus on making a simple build system which detects every javascript file in our source code to obfuscate and minify.

Prerequisites

To follow this tutorial you need basic knowledge of Javascript and Nodejs. We will use javascript-obfuscator to obfuscate and minify code.

Let's go...

Installation

We will only use one external library javascript-obfuscator which can be installed as a dev dependency.

npm install --save-dev javascript-obfuscator

Imports & Folders

In total we need three libraries - fs, path and javascript-obfuscator.

const Fs = require('fs');const Path = require('path');const JavaScriptObfuscator = require('javascript-obfuscator');

The source code will be kept in src folder and final build files will be generated in build folder.

const src = Path.join(__dirname, '/src/');const build = Path.join(__dirname, '/build/');

Read directories

All the directories will be read recursively and find javascript files which will be than obfuscated and minified. To read files we will use fs module.

function readDirectory(dirPath){ Fs.readdir(dirPath, (err, files) => { if(err) { console.error("Could not list directory.", err); process.exit(1); } files.forEach((file, index) => // loop through every file { let path = Path.join(dirPath, file); console.log(path); }); });}

This will give us path of every file and folder in the provided directory. But we need to read differentiate between files and directories and further read the directories found. This can be done through stat function provided by fs.

Fs.stat(path, (err, stat) => { if(err) { console.log("error in stating file.", err); return; } if(stat.isFile()) { console.log(`${path} is a file`); } else if(stat.isDirectory()) { console.log(`${path} is a folder`); readDirectory(path); // Further read the folder. }});

Copy files and directories from src to build directory

Now this is perfect time that we start copying all the files found in src to build directory. While copying we will simultaneously also create absent directories present in src.

if(stat.isFile()){ const newPath = path.replace(src, build); // Replace src path with build path. Fs.copyFileSync(path, newPath); // Copy file from old path in src to new path in build. if(newPath.endsWith(".js")) // Check if it is javascript file. { obfuscate(newPath); // Obfuscate copied file in build folder. }}else if(stat.isDirectory()){ var newDir = path.replace(src, build); // Replace src path with build path. if (!Fs.existsSync(newDir)) // Check if directory exists or not. { Fs.mkdirSync(newDir); // Create new directory. } readDirectory(path); // Further read the folder.}

Obfuscation and Minification

Finally, javascript file found will be obfuscated and minified. To do so, we will use JavaScriptObfuscator.obfuscate function which takes code as first argument and a config object as second.

function obfuscate(filePath){ const content = Fs.readFileSync(filePath).toString(); // Read the files content. var result = JavaScriptObfuscator.obfuscate(content, { // Config for obfuscation compact: true, // Set true to enable minification controlFlowFlattening: true, target: 'browser' } ); // Generated minified and obfuscated code Fs.writeFileSync(filePath, result.getObfuscatedCode()); // Write obfuscted and minified code generated back to file.}

You can read more about the config options here.

Finally...

Here is the full code

const Fs = require('fs');const Path = require('path');const JavaScriptObfuscator = require('javascript-obfuscator');const src = Path.join(__dirname, '/src/');const build = Path.join(__dirname, '/build/');readDirectory(src); // Start reading with src directory.function readDirectory(dirPath){ Fs.readdir(dirPath, (err, files) => { if(err) { console.error("Could not list directory.", err); process.exit(1); } files.forEach((file, index) => // loop through every file { let path = Path.join(dirPath, file); Fs.stat(path, (err, stat) => { if(err) { console.log("error in stating file.", err); return; } if(stat.isFile()) { const newPath = path.replace(src, build); // Replace src path with build path. Fs.copyFileSync(path, newPath); // Copy file from old path in src to new path in build. if(newPath.endsWith(".js")) // Check if it is javascript file. { obfuscate(newPath); // Obfuscate copied file in build folder. } } else if(stat.isDirectory()) { var newDir = path.replace(src, build); // Replace src path with build path. if (!Fs.existsSync(newDir)) // Check if directory exists or not. { Fs.mkdirSync(newDir); // Create new directory. } readDirectory(path); // Further read the folder. } }); }); });}function obfuscate(filePath){ const content = Fs.readFileSync(filePath).toString(); // Read the files content. var result = JavaScriptObfuscator.obfuscate(content, { // Config for obfuscation compact: true, // Set true to enable minification controlFlowFlattening: true, target: 'browser' } ); // Generated minified and obfuscated code Fs.writeFileSync(filePath, result.getObfuscatedCode()); // Write obfuscted and minified code generated back to file.}

Hurray!!! you made till end.
I hope you would have found it useful. If yes, than show some love by commenting and sharing.

Thanks for reading :)

Top comments (5)

Subscribe

Sapir Malka

Sapir Malka

Young fullstack developer based in Israel

  • Location

    Israel

  • Work

    Junior Full stack developer

  • Joined

Jun 21 '20

  • Copy link

Great article!

Sapir Malka

Sapir Malka

Young fullstack developer based in Israel

Jun 21 '20

  • Copy link

Really great code!

Himanshu Mishra

Himanshu Mishra

Hi, My name is Himanshu and I'm an independent maker from India. Currently working on Hoverify- tryhoverify.com

  • Location

    India

  • Work

    Indie Maker

  • Joined

Jun 21 '20

  • Copy link

Thanks

Bdethloff

Bdethloff

  • Joined

May 7 '21

  • Copy link

Thank you so much for this

Visakh Vijayan

Visakh Vijayan

There is nothing else in this world that gives as much happiness as coding

  • Email

    vjnvisakh@gmail.com

  • Location

    Kolkata, West Bengal

  • Education

    MCA

  • Pronouns

    he/him/his

  • Work

    Full Stack Developer at JTC

  • Joined

May 18 '21

  • Copy link

nicely done. Used it in our project. Thanks

For further actions, you may consider blocking this person and/or reporting abuse

Writing simple obfuscation and minification system (2024)

FAQs

What is the difference between obfuscate and minify? ›

Minification is the first step in the obfuscation process. It involves removing whitespace, shortening variable and function names, and stripping comments from the code. Although this technique doesn't truly obfuscate the code, it makes it less readable for humans.

What is an example of obfuscation? ›

Here is an example of deliberate obfuscation: "I cannot say that I do not disagree with you." It allows you to say "you're wrong" but leaves your victim thinking you said "you're right".

What is minified and obfuscated code? ›

Commonly used obfuscators provide many methods that produce different obfuscated versions of the same source code. Minification has similar techniques to obfuscation, but unlike obfuscation, minification reduces the size of the code, which speeds it up and is its primary functionality.

What does obfuscated code look like? ›

Obfuscation in computer code uses complex roundabout phrases and redundant logic to make the code difficult for the reader to understand. The goal is to distract the reader with the complicated syntax of what they are reading and make it difficult for them to determine the true content of the message.

What are the disadvantages of minification? ›

Minification can also introduce errors that are hard to debug. Despite these disadvantages, minification is usually worth attempting for potential performance gains.

What is a small sentence for obfuscate? ›

She was criticized for using arguments that obfuscated the main issue. Companies deliberately obfuscate figures in complicated annual reports. Instead of concealing or obfuscating, the doctors involved admitted their fault and launched an investigation.

What are the disadvantages of obfuscated code? ›

Disadvantages of obfuscation
  • While obfuscation can make reading, writing, and reverse-engineering a program difficult and time-consuming, it will not necessarily make it impossible.
  • It adds time and complexity to the build process for the developers.

What are the techniques of obfuscation? ›

Obfuscation is an umbrella term for a variety of processes that transform data into another form in order to protect sensitive information or personal data. Three of the most common techniques used to obfuscate data are encryption, tokenization, and data masking.

Can Python code be obfuscated? ›

Oxyry Python Obfuscator is a simple web-based tool that you can use to obfuscate the Python code. Simply copy and paste your code and it will generate the obfuscated code. This will rename symbol names, variables, functions, classes, arguments, etc... Avoid 1:1 mapping of cleartext names to obfuscated names.

What is the best code obfuscation software? ›

Some of the best code obfuscation tools include ProGuard for Java bytecode, DexGuard for Android applications, ConfuserEx for . NET assemblies, Dotfuscator, and SmartAssembly. These tools offer features like renaming, string encryption, and control flow obfuscation to make reverse engineering more challenging.

How browsers understand obfuscated code? ›

So, with obfuscation, the browser can access, read, and interpret the obfuscated JavaScript code just as easily as the original, un-obfuscated code. And even though the obfuscated code looks completely different, it will generate precisely the same output in the browser.

Can JavaScript code be obfuscated? ›

Obfuscation: Transform your code to make it hard to steal or copy. A JavaScript Obfuscator will transform your entire source code to make it virtually impossible to read and understand. While the process may modify actual method instructions or metadata, it does not alter the functionality of the program.

What is the purpose of minify? ›

Minification is the process of minimizing code and markup in your web pages and script files. It's one of the main methods used to reduce load times and bandwidth usage on websites. Minification dramatically improves site speed and accessibility, directly translating into a better user experience.

What does it mean for a code to be minified? ›

Minified code refers to the process of removing unnecessary characters and whitespace from a source code file without affecting its functionality. This process is commonly applied to various types of code, such as HTML, CSS, and JavaScript, to optimize website performance.

What is the difference between obfuscate and obscure? ›

Obfuscate means to make something unclear, coming from the Latin obfuscare, meaning to darken. Obscure means to keep from being seen or to conceal, coming from the Latin obscurus, meaning dark.

What is the opposite of obfuscate? ›

Definitions of obfuscate. verb. make obscure or unclear. antonyms: clarify, clear up, elucidate. make clear and (more) comprehensible.

Top Articles
Latest Posts
Article information

Author: Amb. Frankie Simonis

Last Updated:

Views: 5918

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Amb. Frankie Simonis

Birthday: 1998-02-19

Address: 64841 Delmar Isle, North Wiley, OR 74073

Phone: +17844167847676

Job: Forward IT Agent

Hobby: LARPing, Kitesurfing, Sewing, Digital arts, Sand art, Gardening, Dance

Introduction: My name is Amb. Frankie Simonis, I am a hilarious, enchanting, energetic, cooperative, innocent, cute, joyous person who loves writing and wants to share my knowledge and understanding with you.