相關知識講解鏈接 https://blog.csdn.net/qq_24935119/article/details/88577092
對於前端開發中的代碼安全性一直是一個不可忽視的問題,前段時間公司就要求我們把我們小程序端的代碼再進行混淆。看了很多網址,說的不是很明白,因此也就出了這篇文章和大家分享。
1:首先分享一下一個插件鏈接:https://github.com/javascript-obfuscator/javascript-obfuscator。
我用的就是這個javascript-obfuscator插件,這個插件使用教程是對單個文件進行混淆加密。
2:相對的插件工具鏈接:https://www.obfuscator.io/
混淆前:
混淆后:
是不是很好用,這個工具就是基於javascript-obfuscator進行混淆的。但是我們開發過程中常常並不是說把一個js進行混淆就ok了,需要把全量包的js進行混淆。
3:我使用uniapp開發的小程序,需要將編譯過后的小程序代碼再進行混淆,代碼里包含多個js,不同的文件夾下,所以我就在想,用最簡單的遍歷文件的方式進行混淆代碼。
4:首先需要在本機全局安裝 npm install javascript-obfuscator -g
直接上代碼:進入文件夾下控制台,輸入 node obfuscator.js即可進行混淆代碼
index.json
{ "compact": false, "controlFlowFlattening": true, "controlFlowFlatteningThreshold": 1, "numbersToExpressions": true, "simplify": true, "shuffleStringArray": true, "splitStrings": true, "stringArrayThreshold": 1 }
index.js
// 檢索的相對文件夾 const relativePath = '../unpackage/dist/dev/mp-weixin' // 不需要混淆的js或文件夾 const exitFile = ['node_modules', 'index.js', 'app.js', 'common'] var fs = require('fs') var process = require('child_process'); var readDir = fs.readdirSync(relativePath); // 需要存在的js const czFile = [] var filePath = relativePath var arr = new Array() readFile(readDir, filePath) // 讀取相對路徑下的所有文件 function readFile(readDir, filePath) { if (readDir.length > 0) { for (var i = 0; i < readDir.length; i++) { scannerFile(readDir[i], filePath) } } } // 掃描文件進行檢索出js文件進行混淆 function scannerFile(file, filePath) { console.log("file-----" + file); var readdirpath = "" if (filePath == './') { readdirpath = filePath + file } else { readdirpath = filePath + "/" + file } if (exitFile.indexOf(file) < 0) { console.log('-->Start entering FS'); fs.stat(readdirpath, (err, data) => { if (err) { console.log(err); } else { if (data.isDirectory()) { console.log('-->isDirectory:' + file); var readChildDir = fs.readdirSync(readdirpath); console.log(readChildDir); readFile(readChildDir, readdirpath) } else { console.log('-->isNotDirectory:' + file); if (file.indexOf('.js') >= 0 && file.indexOf('.json') < 0) { // 開始混淆代碼 console.log('-->Start confusing code:' + file); var cmd = ' javascript-obfuscator ' + readdirpath + ' --config index.json --output ' + readdirpath; process.exec(cmd, function(error, stdout, stderr) { console.log("error:" + error); console.log("stdout:" + stdout); console.log("stderr:" + stderr); }); arr.push(readdirpath) } else { console.log('Non-folder - Non-js code :' + file); } } } }) } else { console.log('-->skip------------'); } }
使用方式:
————————————————
版權聲明:本文為CSDN博主「背負你的星辰」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_40358970/article/details/112952264