xxtea 文件加密与解密

加密

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)

原文地址:https://www.cnblogs.com/dzqdzq/p/10808213.html

时间: 2024-11-08 20:43:06

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

用openssl对文件加密及解密

Openssl是一个开源的用以实现SSL协议的产品,它主要包括了三个部分:密码算法库.应用程序.SSL协议库.Openssl实现了SSL协议所需要的大多数算法. 下面我将单介绍使用Openssl进行文件的对称加密操作. 一.Openssl支持的加密算法有: -aes-128-cbc -aes-128-cfb -aes-128-cfb1 -aes-128-cfb8 -aes-128-ecb -aes-128-ofb -aes-192-cbc -aes-192-cfb -aes-192-cfb1 -

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

原创整理不易,转载请注明出处:java spring中对properties属性文件加密及其解密 代码下载地址:http://www.zuidaima.com/share/1781588957400064.htm 加密类: package com.zuidaima.commons.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import

文件加密及解密

1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.IO; 5 using System.Runtime.Serialization; 6 using System.Security.Cryptography; 7 8 namespace Sky.Decrypt 9 { 10 /// <summary> 11 /// 解密 12 /// </summary>

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

原文:C#使用RSA证书文件加密和解密示例 修改MSDN上的示例,使之可以通过RSA证书文件加密和解密,中间遇到一个小问题. Q:执行ExportParameters()方法时,回报CryptographicException:该项不适于在指定状态下使用(Key not valid for use in specified state). A:导入带有私钥的证书时,需要使用"X509KeyStorageFlags"参数标记"私钥可导出". X509Certifica

使用Vi/Vim给文件加密和解密

一. 利用vi加密: 优点:加密后,如果不知道密码,就看不到明文,包括root用户也看不了: 缺点:很明显让别人知道加密了,容易让别人把加密的文件破坏掉,包括内容破坏和删除: vi编辑器相信大家都很熟悉了吧,vi里有一个命令是给文件加密的,举个例子吧: 1) 首先在root主目录/root/下建立一个实验文件text.txt: [[email protected] ~]# vi text.txt 2) 进到编辑模式,输入完内容后按ESC,然后输入:X(注意是大写的X),回车: 3) 这时系统提示

C# 文件加密和解密

1.加密 using System;using System.Collections.Generic;using System.Text;using System.Runtime.Serialization;using System.IO;using System.Security.Cryptography; namespace Sky.Encrypt{    /// <summary>    /// 加密    /// </summary>    public class Enc

CryptoJS文件加密与解密

import React, { Component } from 'react';import CryptoJS from 'crypto-js/crypto-js'import { Button } from 'antd'; class Encryption extends Component { constructor(){ super(); this.state={ value2:'qqqqqqqqqqqq', encryptioned:'', Decrypted:'' } } compo

python 加密与解密

加密算法分类 对称加密算法: 对称加密采用了对称密码编码技术,它的特点是文件加密和解密使用相同的密钥 发送方和接收方需要持有同一把密钥,发送消息和接收消息均使用该密钥. 相对于非对称加密,对称加密具有更高的加解密速度,但双方都需要事先知道密钥,密钥在传输过程中可能会被窃取,因此安全性没有非对称加密高. 常见的对称加密算法:DES,AES,3DES等等 非对称加密算法: 文件加密需要公开密钥(publickey)和私有密钥(privatekey). 接收方在发送消息前需要事先生成公钥和私钥,然后将

小例子: 压缩文件时的加密与解密(read + openssl + tar + dd)

1.有的文件需要加密一下 2.有的文件夹需要加密一下 分析: 文件或文件夹加密时需考量的几个问题? 文件夹自动补全时后缀有反斜杠处理规则 单个文件加密时命名的规则 >脚本命令的格式规定为./ss {unEncryptFile | unEncryptDir} >先判断第一个参数是文件还是文件夹 1.文件夹时 > 判断文件夹是否有反斜杠 > 以文件夹的名称做为生成的压缩包名称 2.文件时 > 此处加密时linux中文件后缀去掉 > 当使用压缩和解压缩时后缀就挺有意义的 &g