標籤:
在開發軟體的時候,我們都會在項目上線時候對代碼進行加密,用來防止被不法分子盜走牟利。不同的語言有不同的加密方式,比較出名的有加殼,代碼混淆等。在Lua開發cocos2dx的時候,架構會有提供加密的指令碼。下面我說說加密windows的步驟
1.要知道要加密的源碼的存放路徑,並指定備份路徑
2.把代碼拷貝到備份路徑
3.對所有的指令碼進行去bom處理
4.用php命令compile_scripts.php進行加密處理。
根據以上的四點,我們下面貼出UTF8 去bom的代碼和加密的整體代碼
1.UTF-8
#! /usr/bin/python# -*- coding: utf-8 -*-import osimport sysimport codecsdef convert(dirname, filename):if os.path.splitext(filename)[1] in [‘.txt‘, ‘.py,‘, ‘.lua‘, ‘.sh‘]:path = os.path.join(dirname, filename)print ‘converting %s‘%(path)f = open(path, ‘rb‘)content = f.read(3)if content != ‘\xEF\xBB\xBF‘:print ‘%s is not utf-8 bom‘%(path)returncontent = f.read()f.close()f = open(path, ‘wb‘)f.write(content)f.close()print ‘convert %s finish‘%(path)def useage():if len(sys.argv) == 1:print ‘useage: utf8 file or dir...‘return Truedef exist_error(f):if not os.path.exists(f):print ‘error: %s is not exist‘%(f)return Truedef main():if useage():returnfor f in sys.argv[1:]:if exist_error(f):breakif os.path.isdir(f):for root, dirs, files in os.walk(f):for i in files:convert(root, i)else:convert(‘‘, f)if __name__ == ‘__main__‘:main()
2.compile_scripts.php
<?phpdefine(‘DS‘, DIRECTORY_SEPARATOR);define(‘LUAJIT‘, true);class LuaPackager{ private $quiet = false; private $packageName = ‘‘; private $rootdir = ‘‘; private $rootdirLength = 0; private $suffixName = ‘zip‘; private $files = array(); private $modules = array(); private $excludes = array(); function __construct($config) { $this->quiet = $config[‘quiet‘]; $this->rootdir = realpath($config[‘srcdir‘]); $this->rootdirLength = strlen($this->rootdir) + 1; $this->packageName = trim($config[‘packageName‘], ‘.‘); $this->suffixName = $config[‘suffixName‘]; $this->excludes = $config[‘excludes‘]; if (!empty($this->packageName)) { $this->packageName = $this->packageName . ‘.‘; } } function dumpZip($outputFileBasename) { $this->files = array(); $this->modules = array(); if (!$this->quiet) { print("compile script files\n"); } $this->compile(); if (empty($this->files)) { printf("error.\nERROR: not found script files in %s\n", $this->rootdir); return; } $zipFilename = $outputFileBasename . ‘.‘ . $this->suffixName; $zip = new ZipArchive(); if ($zip->open($zipFilename, ZIPARCHIVE::OVERWRITE | ZIPARCHIVE::CM_STORE)) { if (!$this->quiet) { printf("create ZIP bundle file: %s\n", $zipFilename); } foreach ($this->modules as $module) { $zip->addFromString($module[‘moduleName‘], $module[‘bytes‘]); } $zip->close(); if (!$this->quiet) { printf("done.\n\n"); } } if (!$this->quiet) { print <<<EOT### HOW TO USE ###1. Add code to your lua script: CCLuaLoadChunksFromZip("${zipFilename}")EOT; } } function dump($outputFileBasename) { $this->files = array(); $this->modules = array(); if (!$this->quiet) { print("compile script files\n"); } $this->compile(); if (empty($this->files)) { printf("error.\nERROR: not found script files in %s\n", $this->rootdir); return; } $headerFilename = $outputFileBasename . ‘.h‘; if (!$this->quiet) { printf("create C header file: %s\n", $headerFilename); } file_put_contents($headerFilename, $this->renderHeaderFile($outputFileBasename)); $sourceFilename = $outputFileBasename . ‘.c‘; if (!$this->quiet) { printf("create C source file: %s\n", $sourceFilename); } file_put_contents($sourceFilename, $this->renderSourceFile($outputFileBasename)); if (!$this->quiet) { printf("done.\n\n"); } $outputFileBasename = basename($outputFileBasename); print <<<EOT### HOW TO USE ###1. Add code to AppDelegate.cpp: extern "C" { #include "${outputFileBasename}.h" }2. Add code to AppDelegate::applicationDidFinishLaunching() CCScriptEngineProtocol* pEngine = CCScriptEngineManager::sharedManager()->getScriptEngine(); luaopen_${outputFileBasename}(pEngine->getLuaState()); pEngine->executeString("require(\"main\")");EOT; } private function compile() { if (file_exists($this->rootdir) && is_dir($this->rootdir)) { $this->files = $this->getFiles($this->rootdir); } foreach ($this->files as $path) { $filename = substr($path, $this->rootdirLength); $fi = pathinfo($filename); if ($fi[‘extension‘] != ‘lua‘) continue; $basename = ltrim($fi[‘dirname‘] . DS . $fi[‘filename‘], ‘/\\.‘); $moduleName = $this->packageName . str_replace(DS, ‘.‘, $basename); $found = false; foreach ($this->excludes as $k => $v) { if (substr($moduleName, 0, strlen($v)) == $v) { $found = true; break; } } if ($found) continue; if (!$this->quiet) { printf(‘ compile module: %s...‘, $moduleName); } $bytes = $this->compileFile($path); if ($bytes == false) { print("error.\n"); } else { if (!$this->quiet) { print("ok.\n"); } $bytesName = ‘lua_m_‘ . strtolower(str_replace(‘.‘, ‘_‘, $moduleName)); $this->modules[] = array( ‘moduleName‘ => $moduleName, ‘bytesName‘ => $bytesName, ‘functionName‘ => ‘luaopen_‘ . $bytesName, ‘basename‘ => $basename, ‘bytes‘ => $bytes, ); } } } private function getFiles($dir) { $files = array(); $dir = rtrim($dir, "/\\") . DS; $dh = opendir($dir); if ($dh == false) { return $files; } while (($file = readdir($dh)) !== false) { if ($file{0} == ‘.‘) { continue; } $path = $dir . $file; if (is_dir($path)) { $files = array_merge($files, $this->getFiles($path)); } elseif (is_file($path)) { $files[] = $path; } } closedir($dh); return $files; } private function compileFile($path) { $tmpfile = $path . ‘.bytes‘; if (file_exists($tmpfile)) unlink($tmpfile); if (LUAJIT) { $command = sprintf(‘luajit -b -s "%s" "%s"‘, $path, $tmpfile); } else { $command = sprintf(‘luac -o "%s" "%s"‘, $tmpfile, $path); } passthru($command); if (!file_exists($tmpfile)) return false; $bytes = file_get_contents($tmpfile); unlink($tmpfile); return $bytes; } private function renderHeaderFile($outputFileBasename) { $headerSign = ‘__LUA_MODULES_‘ . strtoupper(md5(time())) . ‘_H_‘; $outputFileBasename = basename($outputFileBasename); $contents = array(); $contents[] = <<<EOT/* ${outputFileBasename}.h */#ifndef ${headerSign}#define ${headerSign}#if __cplusplusextern "C" {#endif#include "lua.h"void luaopen_${outputFileBasename}(lua_State* L);#if __cplusplus}#endifEOT; $contents[] = ‘/*‘; foreach ($this->modules as $module) { $contents[] = sprintf(‘int %s(lua_State* L);‘, $module[‘functionName‘]); } $contents[] = ‘*/‘; $contents[] = <<<EOT#endif /* ${headerSign} */EOT; return implode("\n", $contents); } private function renderSourceFile($outputFileBasename) { $outputFileBasename = basename($outputFileBasename); $contents = array(); $contents[] = <<<EOT/* ${outputFileBasename}.c */#include "lua.h"#include "lauxlib.h"#include "${outputFileBasename}.h"EOT; foreach ($this->modules as $module) { $contents[] = sprintf(‘/* %s, %s.lua */‘, $module[‘moduleName‘], $module[‘basename‘]); $contents[] = sprintf(‘static const unsigned char %s[] = {‘, $module[‘bytesName‘]); // $contents[] = $this->encodeBytes($module[‘bytes‘]); $contents[] = $this->encodeBytesFast($module[‘bytes‘]); $contents[] = ‘};‘; $contents[] = ‘‘; } $contents[] = ‘‘; foreach ($this->modules as $module) { $functionName = $module[‘functionName‘]; $bytesName = $module[‘bytesName‘]; $basename = $module[‘basename‘]; $contents[] = <<<EOTint ${functionName}(lua_State *L) { int arg = lua_gettop(L); luaL_loadbuffer(L, (const char*)${bytesName}, sizeof(${bytesName}), "${basename}.lua"); lua_insert(L,1); lua_call(L,arg,1); return 1;}EOT; } $contents[] = ‘‘; $contents[] = "static luaL_Reg ${outputFileBasename}_modules[] = {"; foreach ($this->modules as $module) { $contents[] = sprintf(‘ {"%s", %s},‘, $module["moduleName"], $module["functionName"]); } $contents[] = <<<EOT {NULL, NULL}};void luaopen_${outputFileBasename}(lua_State* L){ luaL_Reg* lib = ${outputFileBasename}_modules; for (; lib->func; lib++) { lua_getglobal(L, "package"); lua_getfield(L, -1, "preload"); lua_pushcfunction(L, lib->func); lua_setfield(L, -2, lib->name); lua_pop(L, 2); }}EOT; return implode("\n", $contents); } private function encodeBytes($bytes) { $len = strlen($bytes); $contents = array(); $offset = 0; $buffer = array(); while ($offset < $len) { $buffer[] = ord(substr($bytes, $offset, 1)); if (count($buffer) == 16) { $contents[] = $this->encodeBytesBlock($buffer); $buffer = array(); } $offset++; } if (!empty($buffer)) { $contents[] = $this->encodeBytesBlock($buffer); } return implode("\n", $contents); } private function encodeBytesFast($bytes) { $len = strlen($bytes); $output = array(); for ($i = 0; $i < $len; $i++) { $output[] = sprintf(‘%d,‘, ord($bytes{$i})); } return implode(‘‘, $output); } private function encodeBytesBlock($buffer) { $output = array(); $len = count($buffer); for ($i = 0; $i < $len; $i++) { $output[] = sprintf(‘%d,‘, $buffer[$i]); } return implode(‘‘, $output); }}function help(){ echo <<<EOTusage: php compile_scripts.php [options] dirname output_filenameoptions: -zip package to zip -suffix package file extension name -p prefix package name -x exclude packages, eg: -x framework.server, framework.tests -q quietEOT;}if ($argc < 3){ help(); exit(1);}array_shift($argv);$config = array( ‘packageName‘ => ‘‘, ‘excludes‘ => array(), ‘srcdir‘ => ‘‘, ‘outputFileBasename‘ => ‘‘, ‘zip‘ => false, ‘suffixName‘ => ‘zip‘, ‘quiet‘ => false,);do{ if ($argv[0] == ‘-p‘) { $config[‘packageName‘] = $argv[1]; array_shift($argv); } else if ($argv[0] == ‘-x‘) { $excludes = explode(‘,‘, $argv[1]); foreach ($excludes as $k => $v) { $v = trim($v); if (empty($v)) { unset($excludes[$k]); } else { $excludes[$k] = $v; } } $config[‘excludes‘] = $excludes; array_shift($argv); } else if ($argv[0] == ‘-q‘) { $config[‘quiet‘] = true; } else if ($argv[0] == ‘-zip‘) { $config[‘zip‘] = true; } else if ($argv[0] == ‘-suffix‘) { $config[‘suffixName‘] = $argv[1]; array_shift($argv); } else if ($config[‘srcdir‘] == ‘‘) { $config[‘srcdir‘] = $argv[0]; } else { $config[‘outputFileBasename‘] = $argv[0]; } array_shift($argv);} while (count($argv) > 0);$packager = new LuaPackager($config);if ($config[‘zip‘]){ $packager->dumpZip($config[‘outputFileBasename‘]);}else{ $packager->dump($config[‘outputFileBasename‘]);}
3.加密指令碼
@echo onset _P_=bbframeworkset _T_=script_bakcd ..mkdir %_T_%mkdir %_T_%\scriptsmkdir %_P_%\updatescriptsecho "Copy Scripts to bak floder"xcopy /E %_P_%\scripts %_T_%\scripts cd %_P_%echo "UTF-8 transition"python ..\bin\utf8\main.py scriptsecho "Handle <<updatescripts>> Begin.."move /Y scripts/app updatescripts/appphp ..\bin\__lib__\compile_scripts.php -zip -suffix "bin" updatescripts res\updatepause
以上就是windows上對lua代碼進行加密的步驟
本站文章為 寶寶巴士 SD.Team 原創,轉載務必在明顯處註明:(作者官方網站: 寶寶巴士 )
轉載自【寶寶巴士SuperDo團隊】 原文連結: http://www.cnblogs.com/superdo/p/4988378.html
[自動化-指令碼]002.cocos2dx-lua lua代碼windows加密批處理