在开发软件的时候,我们都会在项目上线时候对代码进行加密,用来防止被不法分子盗走牟利。不同的语言有不同的加密方式,比较出名的有加壳,代码混淆等。在Lua开发cocos2dx的时候,框架会有提供加密的脚本。下面我说说加密windows的步骤

1.要知道要加密的源码的存放路径,并指定备份路径

2.把代码拷贝到备份路径

3.对所有的脚本进行去bom处理

4.用php命令compile_scripts.php进行加密处理。

根据以上的四点,我们下面贴出UTF8 去bom的代码和加密的整体代码

1.UTF-8

#! /usr/bin/python
# -*- coding: utf-8 -*- import os
import sys
import codecs def 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)
return
content = 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 True def exist_error(f):
if not os.path.exists(f):
print 'error: %s is not exist'%(f)
return True def main(): if useage():
return for f in sys.argv[1:]:
if exist_error(f):
break
if 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

<?php

define('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 __cplusplus
extern "C" {
#endif #include "lua.h" void luaopen_${outputFileBasename}(lua_State* L); #if __cplusplus
}
#endif EOT; $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[] = <<<EOT int ${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 <<<EOT
usage: php compile_scripts.php [options] dirname output_filename options:
-zip package to zip
-suffix package file extension name
-p prefix package name
-x exclude packages, eg: -x framework.server, framework.tests
-q quiet EOT; } 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 on
set _P_=bbframework
set _T_=script_bak cd ..
mkdir %_T_%
mkdir %_T_%\scripts
mkdir %_P_%\updatescripts echo "Copy Scripts to bak floder"
xcopy /E %_P_%\scripts %_T_%\scripts
cd %_P_% echo "UTF-8 transition"
python ..\bin\utf8\main.py scripts echo "Handle <<updatescripts>> Begin.."
move /Y scripts/app updatescripts/app
php ..\bin\__lib__\compile_scripts.php -zip -suffix "bin" updatescripts res\update pause

以上就是windows上对lua代码进行加密的步骤

本站文章为宝宝巴士 SD.Team原创,转载务必在明显处注明:(作者官方网站:宝宝巴士)

转载自【宝宝巴士SuperDo团队】 原文链接: http://www.cnblogs.com/superdo/p/4988378.html

[自动化-脚本]002.cocos2dx-lua lua代码windows加密批处理的更多相关文章

  1. 如何使用ZEROBRANE STUDIO远程调试COCOS2D-X的LUA脚本(转)

    http://www.cocos2d-x.org/docs/manual/framework/native/v2/lua/lua-remote-debug-via-zerobrane/zh ZeroB ...

  2. Cocos2d-x使用Luajit将Lua脚本编译为bytecode,从而实现加密

    转自:http://www.58player.com/blog-2537-87218.html 项目要求对lua脚本进行加密,查了一下相关的资料 ,得知lua本身可以使用luac将脚本编译为字节码(b ...

  3. cocos2dx的lua绑定

    一.cocos2dx对tolua++绑定的修正 A.c对lua回调函数的引用 在使用cocos2dx编写游戏时,我们经常会设置一些回调函数(时钟.菜单选择等).如果采用脚本方式编写游戏的话,这些回调函 ...

  4. Cocos2d-x下Lua调用自定义C++类和函数的最佳实践[转]

    Cocos2d-x下Lua调用C++这事之所以看起来这么复杂.网上所有的文档都没讲清楚,是因为存在5个层面的知识点: 1.在纯C环境下,把C函数注册进Lua环境,理解Lua和C之间可以互相调用的本质 ...

  5. 【转】Cocos2d-x下Lua调用自定义C++类和函数的最佳实践

    转自:http://segmentfault.com/blog/hongliang/1190000000631630 关于cocos2d-x下Lua调用C++的文档看了不少,但没有一篇真正把这事给讲明 ...

  6. 《Cocos2d-x实战 Lua卷》上线了

    感谢大家一直以来的支持!各大商店均开始销售:京东:http://item.jd.com/11659697.html当当:http://product.dangdang.com/23659810.htm ...

  7. Learning Lua Programming (4) Cocos2d-x中Lua编程(一)

    刚开始接触cocos2d-x 下的Lua编程,主要参看了李华明大神的博客中的介绍,http://blog.csdn.net/xiaominghimi/article/category/1155088  ...

  8. 【Lua学习笔记之:Lua环境搭建 Windows 不用 visual studio】

    Lua 环境搭建 Windows 不用 visual studio 系统环境:Win7 64bit 联系方式:yexiaopeng1992@126.com 前言: 最近需要学习Unity3d游戏中的热 ...

  9. cocos2d-x 使用Lua

    转自:http://www.benmutou.com/blog/archives/49 1. Lua的堆栈和全局表 我们来简单解释一下Lua的堆栈和全局表,堆栈大家应该会比较熟悉,它主要是用来让C++ ...

随机推荐

  1. Spring依赖注入—@Resource注解使用

    1.@Autowired默认按类型装配(这个注解是属业spring的),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowire ...

  2. PinPoint APM搭建全过程

    Pinpoint简介 Pinpoint是一款对Java编写的大规模分布式系统的APM工具,有些人也喜欢称呼这类工具为调用链系统.分布式跟踪系统.我们知道,前端向后台发起一个查询请求,后台服务可能要调用 ...

  3. Java——Spring超详细总结

    Spring概述 一.简化Java开发 Spring为了降低Java开发的复杂性,采用了以下四种策略 基于POJO的轻量级和最小侵入性编程: 通过依赖注入和面向接口实现松耦合: 基于切面和惯例进行声明 ...

  4. Java——异常那些事

    异常的基本定义 异常情形是指阻止当前方法或者作用域继续执行的问题.在这里一定要明确一点:异常代码某种程度的错误,尽管Java有异常处理机制,但是我们不能以“正常”的眼光来看待异常,异常处理机制的原因就 ...

  5. A. Powered Addition(二进制性质-思维)

    \(拿样例来看1 7 6 5\) \(6成长到7是最合理的,因为1s就可以实现而且对于后面来说最优\) \(5成长到7是最合理的,因为2s就可以实现而且对于后面最优\) \(发现了什么?二进制是可以组 ...

  6. dfs+线段树 zhrt的数据结构课

    zhrt的数据结构课 这个题目我觉得是一个有一点点思维的dfs+线段树 虽然说看起来可以用树链剖分写,但是这个题目时间卡了树剖 因为之前用树剖一直在写这个,所以一直想的是区间更新,想dfs+线段树,有 ...

  7. word 小技巧 方框中 打 对勾

    方框中  打 对勾 称为 复选框 控件,单击鼠标,在两种符号中切换. 设置步骤 1. 将隐藏的"开发工具"选项卡,显示出来 2. 在所需位置,插入复选框 3. 在属性中,设置复选框 ...

  8. 07_CSS入门和高级技巧(5)

    超级链接美化 1.伪类 同一个超级链接,根据用户的点击情况,有自己样式: 超级链接根据用户点选情况,有4种状态: a:link 没有访问的超级链接 a:visited 已经访问的超级链接 a:hove ...

  9. 【HBase】带你了解一哈HBase的各种预分区

    目录 简单了解 概述 设置预分区 一.手动指定预分区 二.使用16进制算法生成预分区 三.将分区规则写在文本文件中 四.使用JavaAPI进行预分区 简单了解 概述 由上图可以看出,每一个表都有属于自 ...

  10. 计算机网络——简单说说WebSocket协议

    一.前言   之前做了一个Web小项目,需要实现后端持续给前端推送消息的功能,当时最开始使用的是轮询实现,但是效率太低,对资源消耗也大.之后为了解决这个问题,上网查阅资料后,改用了WebSocket实 ...