加密

cocos luacompile -s src -d dst_dir -e -b xxxxx -k xxxxx --disable-compile

解密

cocos luacompile -s src -d dst_dir -e -j  -b xxxxx -k xxxxx --disable-compile

说明:cocos默认只支持加密,不支持反向解密, 本人改一下python脚本 使其支持解密。 -b 后面接的参数是在文件中可以见的。

#!/usr/bin/python
# ----------------------------------------------------------------------------
# cocos "luacompile" plugin
#
# Copyright 2013 (C) Intel
#
# License: MIT
# ---------------------------------------------------------------------------- '''
"luacompile" plugin for cocos command line tool
''' __docformat__ = 'restructuredtext' import sys
import subprocess
import os
import json
import inspect
import shutil import cocos
from MultiLanguage import MultiLanguage ############################################################
#http://www.coolcode.org/archives/?article-307.html
############################################################ import struct _DELTA = 0x9E3779B9 def _long2str(v, w):
n = (len(v) - 1) << 2
if w:
m = v[-1]
if (m < n - 3) or (m > n): return ''
n = m
s = struct.pack('<%iL' % len(v), *v)
return s[0:n] if w else s def _str2long(s, w):
n = len(s)
m = (4 - (n & 3) & 3) + n
s = s.ljust(m, "\0")
v = list(struct.unpack('<%iL' % (m >> 2), s))
if w: v.append(n)
return v def encrypt(str, key):
if str == '': return str
v = _str2long(str, True)
k = _str2long(key.ljust(16, "\0"), False)
n = len(v) - 1
z = v[n]
y = v[0]
sum = 0
q = 6 + 52 // (n + 1)
while q > 0:
sum = (sum + _DELTA) & 0xffffffff
e = sum >> 2 & 3
for p in xrange(n):
y = v[p + 1]
v[p] = (v[p] + ((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z))) & 0xffffffff
z = v[p]
y = v[0]
v[n] = (v[n] + ((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[n & 3 ^ e] ^ z))) & 0xffffffff
z = v[n]
q -= 1
return _long2str(v, False) def decrypt(str, key):
if str == '': return str
v = _str2long(str, False)
k = _str2long(key.ljust(16, "\0"), False)
n = len(v) - 1
z = v[n]
y = v[0]
q = 6 + 52 // (n + 1)
sum = (q * _DELTA) & 0xffffffff
while (sum != 0):
e = sum >> 2 & 3
for p in xrange(n, 0, -1):
z = v[p - 1]
v[p] = (v[p] - ((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z))) & 0xffffffff
y = v[p]
z = v[n]
v[0] = (v[0] - ((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[0 & 3 ^ e] ^ z))) & 0xffffffff
y = v[0]
sum = (sum - _DELTA) & 0xffffffff
return _long2str(v, True) #import cocos
class CCPluginLuaCompile(cocos.CCPlugin):
"""
compiles (encodes) and minifies Lua files
"""
@staticmethod
def plugin_name():
return "luacompile" @staticmethod
def brief_description():
# returns a short description of this module
return MultiLanguage.get_string('LUACOMPILE_BRIEF') # This is not the constructor, just an initializator
def init(self, options, workingdir):
"""
Arguments:
- `options`:
"""
self._current_src_dir = None
self._src_dir_arr = self.normalize_path_in_list(options.src_dir_arr)
self._dst_dir = options.dst_dir
if not os.path.isabs(self._dst_dir):
self._dst_dir = os.path.abspath(self._dst_dir)
self._verbose = options.verbose
self._workingdir = workingdir
self._lua_files = {}
self._isEncrypt = options.encrypt
self._isDecrypt = options.decrypt
self._encryptkey = options.encryptkey
self._encryptsign = options.encryptsign
self._bytecode_64bit = options.bytecode_64bit self._luajit_exe_path = self.get_luajit_path()
self._disable_compile = options.disable_compile if self._luajit_exe_path is None:
raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_TOOL_NOT_FOUND'),
cocos.CCPluginError.ERROR_TOOLS_NOT_FOUND) self._luajit_dir = os.path.dirname(self._luajit_exe_path) def normalize_path_in_list(self, list):
for i in list:
tmp = os.path.normpath(i)
if not os.path.isabs(tmp):
tmp = os.path.abspath(tmp)
list[list.index(i)] = tmp
return list def get_relative_path(self, luafile):
try:
pos = luafile.index(self._current_src_dir)
if pos != 0:
raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_SRCDIR_NAME_NOT_FOUND'),
cocos.CCPluginError.ERROR_WRONG_ARGS) return luafile[len(self._current_src_dir)+1:]
except ValueError:
raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_SRCDIR_NAME_NOT_FOUND'),
cocos.CCPluginError.ERROR_WRONG_ARGS) def get_output_file_path(self, luafile):
"""
Gets output file path by source lua file
"""
# create folder for generated file
luac_filepath = ""
# Unknow to remove 'c' if self._isDecrypt and luafile.endswith("luac"):
relative_path = self.get_relative_path(luafile)[:-1]
else:
relative_path = self.get_relative_path(luafile)+"c" luac_filepath = os.path.join(self._dst_dir, relative_path) dst_rootpath = os.path.split(luac_filepath)[0]
try:
# print "creating dir (%s)" % (dst_rootpath)
os.makedirs(dst_rootpath)
except OSError:
if os.path.exists(dst_rootpath) == False:
# There was an error on creation, so make sure we know about it
raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_MKDIR_FAILED_FMT',
dst_rootpath),
cocos.CCPluginError.ERROR_PATH_NOT_FOUND) # print "return luac path: "+luac_filepath
return luac_filepath def get_luajit_path(self):
ret = None bit_prefix = "64bit" if self._bytecode_64bit else "32bit"
if cocos.os_is_win32():
ret = os.path.join(self._workingdir, "bin", bit_prefix, "luajit-win32.exe")
elif cocos.os_is_mac():
ret = os.path.join(self._workingdir, "bin", bit_prefix, "luajit-mac")
elif cocos.os_is_linux():
ret = os.path.join(self._workingdir, "bin", bit_prefix, "luajit-linux") print("luajit bin path: " + ret)
return ret def compile_lua(self, lua_file, output_file):
"""
Compiles lua file
"""
cocos.Logging.debug(MultiLanguage.get_string('LUACOMPILE_DEBUG_COMPILE_FILE_FMT', lua_file)) with cocos.pushd(self._luajit_dir):
cmd_str = "\"%s\" -b \"%s\" \"%s\"" % (self._luajit_exe_path, lua_file, output_file)
self._run_cmd(cmd_str) # TODO
# def compress_js(self):
def deep_iterate_dir(self, rootDir):
for lists in os.listdir(rootDir):
path = os.path.join(rootDir, lists)
if os.path.isdir(path):
self.deep_iterate_dir(path)
elif os.path.isfile(path):
if os.path.splitext(path)[1] in (".lua" ,".luac"):
self._lua_files[self._current_src_dir].append(path) # UNDO
# def index_in_list(self, lua_file, l):
# def lua_filename_pre_order_compare(self, a, b):
# def lua_filename_post_order_compare(self, a, b):
# def _lua_filename_compare(self, a, b, files, delta):
# def reorder_lua_files(self): def handle_all_lua_files(self):
"""
Arguments:
- `self`:
"""
skipLen = len(self._encryptsign)
cocos.Logging.info(MultiLanguage.get_string('LUACOMPILE_INFO_PROCESS_FILE'))
index = 0
for src_dir in self._src_dir_arr:
for lua_file in self._lua_files[src_dir]:
self._current_src_dir = src_dir
dst_lua_file = self.get_output_file_path(lua_file)
if self._disable_compile:
shutil.copy(lua_file, dst_lua_file)
else:
self.compile_lua(lua_file, dst_lua_file) if self._isEncrypt == True:
bytesFile = open(dst_lua_file, "rb+")
encryBytes = None
if self._isDecrypt:
encryBytes = decrypt(bytesFile.read()[skipLen:], self._encryptkey)
else:
encryBytes = encrypt(bytesFile.read(), self._encryptkey)
encryBytes = self._encryptsign + encryBytes
bytesFile.seek(0)
bytesFile.write(encryBytes)
bytesFile.close()
index = index + 1 def run(self, argv, dependencies):
"""
"""
self.parse_args(argv) # tips
cocos.Logging.warning(MultiLanguage.get_string('LUACOMPILE_WARNING_TIP_MSG'))
# create output directory
try:
os.makedirs(self._dst_dir)
except OSError:
if os.path.exists(self._dst_dir) == False:
raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_MKDIR_FAILED_FMT',
self._dst_dir),
cocos.CCPluginError.ERROR_PATH_NOT_FOUND) # deep iterate the src directory
for src_dir in self._src_dir_arr:
self._current_src_dir = src_dir
self._lua_files[self._current_src_dir] = []
self.deep_iterate_dir(src_dir) self.handle_all_lua_files() cocos.Logging.info(MultiLanguage.get_string('LUACOMPILE_INFO_FINISHED')) def parse_args(self, argv):
"""
""" from argparse import ArgumentParser parser = ArgumentParser(prog="cocos %s" % self.__class__.plugin_name(),
description=self.__class__.brief_description()) parser.add_argument("-v", "--verbose",
action="store_true",
dest="verbose",
help=MultiLanguage.get_string('LUACOMPILE_ARG_VERBOSE'))
parser.add_argument("-s", "--src", dest="src_dir_arr",
action="append", help=MultiLanguage.get_string('LUACOMPILE_ARG_SRC'))
parser.add_argument("-d", "--dst", dest="dst_dir",
help=MultiLanguage.get_string('LUACOMPILE_ARG_DST'))
parser.add_argument("-e", "--encrypt",
action="store_true", dest="encrypt",default=False,
help=MultiLanguage.get_string('LUACOMPILE_ARG_ENCRYPT'))
parser.add_argument("-j", "--decrypt",
action="store_true", dest="decrypt",default=False,
help=MultiLanguage.get_string('LUACOMPILE_ARG_ENCRYPT'))
parser.add_argument("-k", "--encryptkey",
dest="encryptkey",default="2dxLua",
help=MultiLanguage.get_string('LUACOMPILE_ARG_ENCRYPT_KEY'))
parser.add_argument("-b", "--encryptsign",
dest="encryptsign",default="XXTEA",
help=MultiLanguage.get_string('LUACOMPILE_ARG_ENCRYPT_SIGN'))
parser.add_argument("--disable-compile",
action="store_true", dest="disable_compile", default=False,
help=MultiLanguage.get_string('LUACOMPILE_ARG_DISABLE_COMPILE'))
parser.add_argument("--bytecode-64bit",
action="store_true", dest="bytecode_64bit", default=False,
help=MultiLanguage.get_string('LUACOMPILE_ARG_BYTECODE_64BIT')) options = parser.parse_args(argv) if options.src_dir_arr == None:
raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_SRC_NOT_SPECIFIED'),
cocos.CCPluginError.ERROR_WRONG_ARGS)
elif options.dst_dir == None:
raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_DST_NOT_SPECIFIED'),
cocos.CCPluginError.ERROR_WRONG_ARGS)
else:
for src_dir in options.src_dir_arr:
if os.path.exists(src_dir) == False:
raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_DIR_NOT_EXISTED_FMT')
% (src_dir), cocos.CCPluginError.ERROR_PATH_NOT_FOUND) # script directory
if getattr(sys, 'frozen', None):
workingdir = os.path.realpath(os.path.dirname(sys.executable))
else:
workingdir = os.path.realpath(os.path.dirname(__file__)) self.init(options, workingdir)

xxtea 文件加密与解密的更多相关文章

  1. C#使用RSA证书文件加密和解密示例

    修改MSDN上的示例,使之可以通过RSA证书文件加密和解密,中间遇到一个小问题. Q:执行ExportParameters()方法时,回报CryptographicException:该项不适于在指定 ...

  2. base64和Xxtea的加密和解密

    base64和Xxtea的加密和解密 数据加密是web数据安全的一种方式,前几天拿到一个base64+xxtea加密的数据,现在在这里整理一下使用的过程.首先当然是全网站找解密方法,但是最后的结果不是 ...

  3. TEA加密算法的文件加密和解密的实现

    一.TEA加密算法简介 TEA加密算法是由英国剑桥大学计算机实验室提出的一种对称分组加密算法.它采用扩散和混乱方法,对64位的明文数据块,用128位密钥分组进行加密,产生64位的密文数据块,其循环轮数 ...

  4. Android中文件加密和解密的实现

    最近项目中需要用到加解密功能,言外之意就是不想让人家在反编译后通过不走心就能获取文件里一些看似有用的信息,但考虑到加解密的简单实现,这里并不使用AES或DES加解密 为了对android中assets ...

  5. C#使用RSA证书文件加密和解密

    public class EncrypHelp { static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKey ...

  6. java spring中对properties属性文件加密及其解密

    http://blog.csdn.net/yaerfeng/article/details/26561791

  7. Java实现文件的加密与解密

    最近在做一个项目,需要将资源文件(包括图片.动画等类型)进行简单的加密后再上传至云上的服务器,而在应用程序中对该资源使用前先将读取到的文件数据进行解密以得到真正的文件信息.此策略的原因与好处是将准备好 ...

  8. Python加密与解密

    前言 据记载,公元前400年,古希腊人发明了置换密码.1881年世界上的第一个电话 保密专利出现.在第二次世界大战期间,德国军方启用“恩尼格玛”密码机, 密码学在战争中起着非常重要的作用. 随着信息化 ...

  9. python 加密与解密

    加密算法分类 对称加密算法: 对称加密采用了对称密码编码技术,它的特点是文件加密和解密使用相同的密钥 发送方和接收方需要持有同一把密钥,发送消息和接收消息均使用该密钥. 相对于非对称加密,对称加密具有 ...

随机推荐

  1. C++ 多线程与并发

    1. 非原子操作 这些非原子操作在被编译为汇编代码后不止一条指令. 自加.自减少: new 关键字: 申请内存: 调用构造函数: pInst = new T; // 对于这样一个赋值语句,更是包含了如 ...

  2. bzoj 2006 超级钢琴 —— ST表

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=2006 本来应该是可以用主席树,找区间最小值,取出来后再找那段区间的次小值...... 但也可 ...

  3. VS2013Xml文件节点导航插件开发

    一.功能描述 该插件的功能跟代码文件的导航功能类似,只是下拉框里的内容是元素的某一属性值,如图-1所示 图-1 当点击下拉框的选项后,会自动定位到该内容在xml文件的位置.此功能适用于xml文件内容较 ...

  4. 10_传智播客iOS视频教程_NSString

    从今天开始不会再去用C语言当中的字符串.因为OC当中设计了一种更为好用的存储字符串的变量. C的字符串和OC的字符串是有区别的. NSString类型的指针变量,只能存储OC字符串的地址.第一步是声明 ...

  5. EF 连接MySql

    使用EntityFramework6连接MySql数据库(db first方式) http://www.cnblogs.com/24la/archive/2014/04/03/ef6-mysql.ht ...

  6. bzoj2131: 免费的馅饼(树状数组)

    Description Input 第一行是用空格隔开的二个正整数,分别给出了舞台的宽度W(1到10^8之间)和馅饼的个数n(1到10^5). 接下来n行,每一行给出了一块馅饼的信息.由三个正整数组成 ...

  7. vue中使用element写点击input内部标签(使用模态框传值)

    首先附上源码地址 https://files.cnblogs.com/files/maruihua/vue-tagsinput-master.zip 这个是我修改后的代码.取消了部分功能,添加的一些功 ...

  8. PowerDesigner在PDM转换为sql脚本时报错Generation aborted due to errors detected during the verification of the mod

    在设计概念数据模型(CDM)之后,转换为物理数据模型(PDM),之后转换为sql脚本时报错Generation aborted due to errors detected during the ve ...

  9. Linux环境下MySQL5.7安装记录

    参考文档 <Installing MySQL on Unix/Linux Using Generic Binaries> https://dev.mysql.com/doc/refman/ ...

  10. Latex排版工具的使用(二) 分类: Latex 2014-06-14 23:01 389人阅读 评论(0) 收藏

    Latex可以支持中文排版,如何实现中文支持可以到网上查找教程. 下面编写一段对中文排版的Latex源文档: 新建文件second.tex: \documentclass{article} \usep ...