`cocos2dx非完整` 添加xxtea加密模块

时间:2023-03-09 03:29:53
`cocos2dx非完整` 添加xxtea加密模块

在上一篇文章中,我已经开始着手写自己的模块,也就是fw部分.其中上一篇文章中完成的是lua部分的配置解析部分,涉及一点点平台方面的封装.这一片文章我来说明一下我是如何处理cocos2dx资源加密的.首先需要说明白的是,资源是什么?资源分为哪几类?

在选择使用lua脚本开发后,包括lua文件,游戏美术资源,游戏的配置,我都统称为游戏资源,所以我期望的加密是能够加密所有这些东西.quick提供了xxtea,而cocos2dx也在luastack中整合了xxtea,我稍微做了一些修改.主要的修改思路是:首先要知道lua文件,游戏资源文件的加载入口在哪里.也许很多人听到我这么说会觉得很怪,不过这确实是解决这个问题的根本出发点.只要找到了加载入口才能做出合适的解决方案.

通过查看源码,我发现lua_loader加载lua文件的入口其实就是fileutils中的接口,然后使用vs的debug,又定位到fileutils中的文件Io读取接口.这样子就知道我们需要手动操作的接口了。我们就看其中一个接口就好了.

CCFileUtils-win32.cpp

 static Data getData(const std::string& filename, bool forString)
{
if (filename.empty())
{
return Data::Null;
} unsigned char *buffer = nullptr; size_t size = ;
do
{
// read the file from hardware
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename); WCHAR wszBuf[CC_MAX_PATH] = {};
MultiByteToWideChar(CP_UTF8, , fullPath.c_str(), -, wszBuf, sizeof(wszBuf)/sizeof(wszBuf[])); HANDLE fileHandle = ::CreateFileW(wszBuf, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, nullptr);
CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE); size = ::GetFileSize(fileHandle, nullptr); if (forString)
{
buffer = (unsigned char*) malloc(size + );
buffer[size] = '\0';
}
else
{
buffer = (unsigned char*) malloc(size);
}
DWORD sizeRead = ;
BOOL successed = FALSE;
successed = ::ReadFile(fileHandle, buffer, size, &sizeRead, nullptr);
::CloseHandle(fileHandle); if (!successed)
{
free(buffer);
buffer = nullptr;
}
} while (); Data ret; if (buffer == nullptr || size == )
{
std::string msg = "Get data from file(";
// Gets error code.
DWORD errorCode = ::GetLastError();
char errorCodeBuffer[] = {};
snprintf(errorCodeBuffer, sizeof(errorCodeBuffer), "%d", errorCode); msg = msg + filename + ") failed, error code is " + errorCodeBuffer;
CCLOG("%s", msg.c_str());
}
else
{
unsigned long len = ;
unsigned char* retbuf = FWResEncrypt::getInstance()->decryptData(buffer, size, &len);
//ret.fastSet(buffer, size);
ret.fastSet(retbuf, len);
}
return ret;
}

如果读取文件成功的话,在62行中buffer保存的就是从文件读取的字符流. 所以如果资源文件是被加密的,那么我们只需要在这个时候进行相关的解密操作然后调用ret.fastSet接口传入解密后的字符就行了。也就是上面我修改的那几句代码,请具体参考源码文件对比.好了,知道这么做以后我们就去看一下xxtea的操作方式.xxtea是在external提供过得第三方扩展,其实这是一个比较旧的版本,不过引擎自带的,我也懒得去添加新的了.看下面我从CCLuaStack.cpp中截取的部分代码,观察一下xxtea加密接口的使用.

 int LuaStack::luaLoadBuffer(lua_State *L, const char *chunk, int chunkSize, const char *chunkName)
{
int r = ; if (_xxteaEnabled && strncmp(chunk, _xxteaSign, _xxteaSignLen) == )
{
// decrypt XXTEA
xxtea_long len = ;
unsigned char* result = xxtea_decrypt((unsigned char*)chunk + _xxteaSignLen,
(xxtea_long)chunkSize - _xxteaSignLen,
(unsigned char*)_xxteaKey,
(xxtea_long)_xxteaKeyLen,
&len);
r = luaL_loadbuffer(L, (char*)result, len, chunkName);
free(result);
}
else
{
r = luaL_loadbuffer(L, chunk, chunkSize, chunkName);
}

然后继续观察其他部分的使用,如xxtea签名的设置:

 void LuaStack::setXXTEAKeyAndSign(const char *key, int keyLen, const char *sign, int signLen)
{
cleanupXXTEAKeyAndSign(); if (key && keyLen && sign && signLen)
{
_xxteaKey = (char*)malloc(keyLen);
memcpy(_xxteaKey, key, keyLen);
_xxteaKeyLen = keyLen; _xxteaSign = (char*)malloc(signLen);
memcpy(_xxteaSign, sign, signLen);
_xxteaSignLen = signLen; _xxteaEnabled = true;
}
else
{
_xxteaEnabled = false;
}
} void LuaStack::cleanupXXTEAKeyAndSign()
{
if (_xxteaKey)
{
free(_xxteaKey);
_xxteaKey = nullptr;
_xxteaKeyLen = ;
}
if (_xxteaSign)
{
free(_xxteaSign);
_xxteaSign = nullptr;
_xxteaSignLen = ;
}
}

好了,有了这些作为基础,我们可以动手写自己的加密管理类了。为什么说要另外写,很多人第一反应可能是在引擎中添加更方便.不可那么做,第一,不应该随便修改引擎核心部分的源码,除非迫不得已.第二,我们这边的情况确实不应该在libluacocos2dx vs项目中去做.因为libluacocos2dx对libcocos2dx是依赖关系,不应该前后倒置。所以第一步是用VS打开项目解决方案.然后在libcocos2dx extern筛选器下面再添加一个删选器,命名为xxtea,然后加入cocos2dx/extern/xxtea下面的xxtea第三方依赖源码.第二步,由于fileutils涉及到跨平台部分,所以我们应该提供一个加密操作类,放在cocos/platform下面是我认为比较合适的位置.所以我添加了如下的源码:

 #ifndef __firework_ResEncrypt__
#define __firework_ResEncrypt__ #include "platform/CCPlatformMacros.h" class CC_DLL FWResEncrypt
{
public:
static FWResEncrypt* getInstance(); public:
unsigned char* decryptData(unsigned char* buf, unsigned long size, unsigned long *pSize);
unsigned char* getFileData(const char* fileName, const char* mode, unsigned long *pSize);
unsigned char* encryptData(unsigned char* buf, unsigned long size, unsigned long *pSize);
void setXXTeaKeyAndSign(const char* xxteaKey, int xxteaKeyLen, const char* xxteaSign, int xxteaSignLen);
void cleanupXXTeaKeyAndSign();
private:
static FWResEncrypt* pFWResEncrypt_; bool xxteaEnabled_;
char* xxteaKey_;
int xxteaKeyLen_;
char* xxteaSign_;
int xxteaSignLen_;
private:
FWResEncrypt();
FWResEncrypt(const FWResEncrypt&);
FWResEncrypt& operator = (const FWResEncrypt&);
}; #endif
#include "FWResEncrypt.h"
#include "cocos2d.h"
#include "CCFileUtils.h"
#include "xxtea/xxtea.h" FWResEncrypt* FWResEncrypt::pFWResEncrypt_ = nullptr; FWResEncrypt* FWResEncrypt::getInstance()
{
if(!pFWResEncrypt_)
{
pFWResEncrypt_ = new FWResEncrypt();
}
return pFWResEncrypt_;
} FWResEncrypt::FWResEncrypt()
:xxteaEnabled_(false)
,xxteaKey_(nullptr)
,xxteaKeyLen_()
,xxteaSign_(nullptr)
,xxteaSignLen_()
{ } void FWResEncrypt::setXXTeaKeyAndSign(const char* xxteaKey, int xxteaKeyLen, const char* xxteaSign, int xxteaSignLen)
{
cleanupXXTeaKeyAndSign(); if( xxteaKey && xxteaKeyLen && xxteaSign && xxteaSignLen)
{
xxteaKey_ = (char*)malloc(xxteaKeyLen);
memcpy(xxteaKey_, xxteaKey, xxteaKeyLen);
xxteaKeyLen_ = xxteaKeyLen; xxteaSign_ = (char*)malloc(xxteaSignLen);
memcpy(xxteaSign_, xxteaSign, xxteaSignLen);
xxteaSignLen_ = xxteaSignLen; xxteaEnabled_ = true;
} else
{
xxteaEnabled_ = false;
}
} void FWResEncrypt::cleanupXXTeaKeyAndSign()
{
if(xxteaKey_)
{
free(xxteaKey_);
xxteaKey_ = nullptr;
xxteaKeyLen_ = ;
}
if(xxteaSign_)
{
free(xxteaSign_);
xxteaSign_ = nullptr;
xxteaSignLen_ = ;
}
} unsigned char* FWResEncrypt::getFileData(const char* fileName, const char* mode, unsigned long* pSize)
{
ssize_t size;
unsigned char* buf = cocos2d::FileUtils::getInstance()->getFileData(fileName, mode, &size);
if(nullptr == buf)
{
return nullptr;
} unsigned char* buffer = nullptr;
FWResEncrypt* pFWResEncrypt = FWResEncrypt::getInstance(); bool isXXTEA = pFWResEncrypt && pFWResEncrypt->xxteaEnabled_; for(unsigned int i = ; isXXTEA && i < pFWResEncrypt->xxteaSignLen_ && i < size; ++ i )
{
isXXTEA = buf[i] == pFWResEncrypt->xxteaSign_[i];
} if(isXXTEA)
{
xxtea_long len = ;
buffer = xxtea_decrypt( buf+pFWResEncrypt->xxteaSignLen_,
(xxtea_long)size - (xxtea_long)pFWResEncrypt->xxteaSignLen_,
(unsigned char*)pFWResEncrypt->xxteaKey_,
(xxtea_long)pFWResEncrypt->xxteaKeyLen_, &len);
delete [] buf;
buf = nullptr;
size = len;
} else
{
buffer = buf;
} if(pSize)
{
*pSize = size;
}
return buffer;
} unsigned char *FWResEncrypt::decryptData(unsigned char* buf, unsigned long size, unsigned long* pSize)
{
CCAssert(buf != nullptr, "decryptData buf cannot nullptr"); unsigned char* buffer = nullptr;
FWResEncrypt* pFWResEncrypt = FWResEncrypt::getInstance();
bool isXXTEA = pFWResEncrypt && pFWResEncrypt->xxteaEnabled_; for(unsigned int i = ; isXXTEA && i < pFWResEncrypt->xxteaSignLen_ && i < size; ++ i )
{
isXXTEA = buf[i] == pFWResEncrypt->xxteaSign_[i];
} if(isXXTEA)
{
xxtea_long len = ;
buffer = xxtea_decrypt( buf+pFWResEncrypt->xxteaSignLen_,
(xxtea_long)size - (xxtea_long)pFWResEncrypt->xxteaSignLen_,
(unsigned char*)pFWResEncrypt->xxteaKey_,
(xxtea_long)pFWResEncrypt->xxteaKeyLen_, &len);
delete [] buf;
buf = nullptr;
size = len;
} else
{
buffer = buf;
}
if(pSize)
{
*pSize = size;
}
return buffer;
} unsigned char* FWResEncrypt::encryptData(unsigned char* buf, unsigned long size, unsigned long* pSize)
{
CCAssert(buf != nullptr, "encryptData buf cannot nullptr");
unsigned char* buffer = nullptr;
unsigned char* ret = nullptr;
FWResEncrypt* pFWResEncrypt = FWResEncrypt::getInstance();
bool isXXTEA = pFWResEncrypt && pFWResEncrypt->xxteaEnabled_;
for(unsigned int i = ; isXXTEA && i < pFWResEncrypt->xxteaSignLen_ && i < size; ++ i )
{
isXXTEA = buf[i] == pFWResEncrypt->xxteaSign_[i];
}
if(!isXXTEA)
{
xxtea_long len = ;
buffer = xxtea_encrypt( buf,
(xxtea_long)size,
(unsigned char*)pFWResEncrypt->xxteaKey_,
(xxtea_long)pFWResEncrypt->xxteaKeyLen_, &len);
delete [] buf;
buf = nullptr;
size = len;
ret = (unsigned char*)malloc(size+pFWResEncrypt->xxteaSignLen_+);
memcpy(ret, pFWResEncrypt->xxteaSign_, pFWResEncrypt->xxteaSignLen_);
memcpy(ret+pFWResEncrypt->xxteaSignLen_, buffer, size);
ret[len+pFWResEncrypt->xxteaSignLen_] = '\0';
} else
{
ret = buf;
}
if(pSize)
{
*pSize = size+pFWResEncrypt->xxteaSignLen_;
}
return ret;
}

其中设置签名,清除签名那些方法我都是直接从CCLuaStack中拿过来的,加密接口也可以直接从那边改一下就好了,最主要的是decryptData这个接口,也就是解密接口. 我发现xxtea提供的sign的功能就是用来同时解析加密和非加密文件,也就是直接加载文件头.如果我的Sign是FW的话,那么我会发现我加密后文件头就有FW.所以加密接口实现的思路是使用xxtea加密,得到加密后的字符串,再做字符串操作,将Sign拼接到加密字符串前面,也就是生成一个新的字符串,再写入文件流就行了.好了,下面我给出我绑定接口到lua的源码:

 #include "lua_fw_encrypt.h"
#if __cplusplus
extern "C" {
#endif
#include <lualib.h>
#include <lauxlib.h>
#if __cplusplus
}
#endif #include <string>
#include "FWResEncrypt.h"
#include "cocos2d.h"
int
lua_fw_encrypt_encryptData(lua_State* lua_state)
{
std::string data = lua_tostring(lua_state, );
unsigned char* encryptData = (unsigned char*)malloc(data.size());
memcpy(encryptData, data.c_str(), data.size());
unsigned long len = ;
unsigned char* encryptedData = FWResEncrypt::getInstance()->encryptData(encryptData, data.size(), &len);
lua_pushlstring(lua_state, (char*)encryptedData, len);
return ;
}
int
lua_fw_encrypt_decryptData(lua_State* lua_state)
{
size_t len = ;
const char *data = lua_tolstring(lua_state, ,&len);
unsigned char* decryptData = (unsigned char*)malloc(len);
memcpy(decryptData, data, len);
unsigned char* decryptedData = FWResEncrypt::getInstance()->decryptData(decryptData, len, nullptr);
lua_pushstring(lua_state, (char*)decryptedData);
return ;
} namespace fw {
const luaL_Reg
g_fw_encrypt_funcs[] = {
{"encrypt_data", lua_fw_encrypt_encryptData},
{"decrypt_data", lua_fw_encrypt_decryptData},
{nullptr,nullptr},
}; void
register_fw_encrypt(lua_State* lua_state) {
luaL_register(lua_state, "fw.encrypt", g_fw_encrypt_funcs);
}
}

我并不喜欢cocos2dx使用的tolua++的方式绑定接口,会生成太多冗余的代码,而是采用传统的C方式去做这件事情,这里面注意lua_pushlstring的使用,为什么要用这个接口?而不是直接使用lua_pushstring.这个问题可能是因为引擎绑定的lua源码中做了一些修改(我是这样推测的),因为使用lua_pushstring错误,应该是不能正确获取指针指向的字符长度.改用lua_pushlstring传入长度len就可以解决这个问题了.

下面也是我在lua那边fw模块做了一下简单的包装,非常的简单.这么做的目的就是能够让使用lua的人不关心c++部分的实现,不会觉得这个接口出现的莫名其妙.

 --小岩<757011285@qq.com>
--2015-5-26 16:45
return
{
encrypt = fw.encrypt.encrypt_data,
decrypt = fw.encrypt.decrypt_data,
}

好了,有了这个加解密的接口,我们就可以在配置文件读取的那部分做一下修改,在持久化和读取的时候就可以正确读取了.如果是windows需要修改platform下面ccFileutils-win32.cpp中的接口,如果是android则对用修改ccFileutils-android.cpp中的接口.我给一下源码:(android同样):

 /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/ #include "platform/CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #include "CCFileUtils-win32.h"
#include "platform/CCCommon.h"
#include <Shlobj.h>
#include "FWResEncrypt.h"
using namespace std; NS_CC_BEGIN #define CC_MAX_PATH 512 // The root path of resources, the character encoding is UTF-8.
// UTF-8 is the only encoding supported by cocos2d-x API.
static std::string s_resourcePath = ""; // D:\aaa\bbb\ccc\ddd\abc.txt --> D:/aaa/bbb/ccc/ddd/abc.txt
static inline std::string convertPathFormatToUnixStyle(const std::string& path)
{
std::string ret = path;
int len = ret.length();
for (int i = ; i < len; ++i)
{
if (ret[i] == '\\')
{
ret[i] = '/';
}
}
return ret;
} static void _checkPath()
{
if ( == s_resourcePath.length())
{
WCHAR utf16Path[CC_MAX_PATH] = {};
GetCurrentDirectoryW(sizeof(utf16Path)-, utf16Path); char utf8Path[CC_MAX_PATH] = {};
int nNum = WideCharToMultiByte(CP_UTF8, , utf16Path, -, utf8Path, sizeof(utf8Path), nullptr, nullptr); s_resourcePath = convertPathFormatToUnixStyle(utf8Path);
s_resourcePath.append("/");
}
} FileUtils* FileUtils::getInstance()
{
if (s_sharedFileUtils == nullptr)
{
s_sharedFileUtils = new FileUtilsWin32();
if(!s_sharedFileUtils->init())
{
delete s_sharedFileUtils;
s_sharedFileUtils = nullptr;
CCLOG("ERROR: Could not init CCFileUtilsWin32");
}
}
return s_sharedFileUtils;
} FileUtilsWin32::FileUtilsWin32()
{
} bool FileUtilsWin32::init()
{
_checkPath();
_defaultResRootPath = s_resourcePath;
return FileUtils::init();
} bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const
{
if ( == strFilePath.length())
{
return false;
} std::string strPath = strFilePath;
if (!isAbsolutePath(strPath))
{ // Not absolute path, add the default root path at the beginning.
strPath.insert(, _defaultResRootPath);
} WCHAR utf16Buf[CC_MAX_PATH] = {};
MultiByteToWideChar(CP_UTF8, , strPath.c_str(), -, utf16Buf, sizeof(utf16Buf)/sizeof(utf16Buf[])); DWORD attr = GetFileAttributesW(utf16Buf);
if(attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY))
return false; // not a file
return true;
} bool FileUtilsWin32::isAbsolutePath(const std::string& strPath) const
{
if ( strPath.length() >
&& ( (strPath[] >= 'a' && strPath[] <= 'z') || (strPath[] >= 'A' && strPath[] <= 'Z') )
&& strPath[] == ':')
{
return true;
}
return false;
} static Data getData(const std::string& filename, bool forString)
{
if (filename.empty())
{
return Data::Null;
} unsigned char *buffer = nullptr; size_t size = ;
do
{
// read the file from hardware
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename); WCHAR wszBuf[CC_MAX_PATH] = {};
MultiByteToWideChar(CP_UTF8, , fullPath.c_str(), -, wszBuf, sizeof(wszBuf)/sizeof(wszBuf[])); HANDLE fileHandle = ::CreateFileW(wszBuf, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, nullptr);
CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE); size = ::GetFileSize(fileHandle, nullptr); if (forString)
{
buffer = (unsigned char*) malloc(size + );
buffer[size] = '\0';
}
else
{
buffer = (unsigned char*) malloc(size);
}
DWORD sizeRead = ;
BOOL successed = FALSE;
successed = ::ReadFile(fileHandle, buffer, size, &sizeRead, nullptr);
::CloseHandle(fileHandle); if (!successed)
{
free(buffer);
buffer = nullptr;
}
} while (); Data ret; if (buffer == nullptr || size == )
{
std::string msg = "Get data from file(";
// Gets error code.
DWORD errorCode = ::GetLastError();
char errorCodeBuffer[] = {};
snprintf(errorCodeBuffer, sizeof(errorCodeBuffer), "%d", errorCode); msg = msg + filename + ") failed, error code is " + errorCodeBuffer;
CCLOG("%s", msg.c_str());
}
else
{
unsigned long len = ;
unsigned char* retbuf = FWResEncrypt::getInstance()->decryptData(buffer, size, &len);
//ret.fastSet(buffer, size);
ret.fastSet(retbuf, len);
}
return ret;
} std::string FileUtilsWin32::getStringFromFile(const std::string& filename)
{
Data data = getData(filename, true);
if (data.isNull())
{
return "";
} std::string ret((const char*)data.getBytes());
return ret;
} Data FileUtilsWin32::getDataFromFile(const std::string& filename)
{
return getData(filename, false);
} unsigned char* FileUtilsWin32::getFileData(const std::string& filename, const char* mode, ssize_t* size)
{
unsigned char * pBuffer = nullptr;
*size = ;
do
{
// read the file from hardware
std::string fullPath = fullPathForFilename(filename); WCHAR wszBuf[CC_MAX_PATH] = {};
MultiByteToWideChar(CP_UTF8, , fullPath.c_str(), -, wszBuf, sizeof(wszBuf)/sizeof(wszBuf[])); HANDLE fileHandle = ::CreateFileW(wszBuf, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, nullptr);
CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE); *size = ::GetFileSize(fileHandle, nullptr); pBuffer = (unsigned char*) malloc(*size);
DWORD sizeRead = ;
BOOL successed = FALSE;
successed = ::ReadFile(fileHandle, pBuffer, *size, &sizeRead, nullptr);
::CloseHandle(fileHandle); if (!successed)
{
free(pBuffer);
pBuffer = nullptr;
}
} while (); if (! pBuffer)
{
std::string msg = "Get data from file(";
// Gets error code.
DWORD errorCode = ::GetLastError();
char errorCodeBuffer[] = {};
snprintf(errorCodeBuffer, sizeof(errorCodeBuffer), "%d", errorCode); msg = msg + filename + ") failed, error code is " + errorCodeBuffer;
CCLOG("%s", msg.c_str());
}
//return pBuffer;
return FWResEncrypt::getInstance()->decryptData(pBuffer, *size, (unsigned long*)size);
} std::string FileUtilsWin32::getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath)
{
std::string unixFileName = convertPathFormatToUnixStyle(filename);
std::string unixResolutionDirectory = convertPathFormatToUnixStyle(resolutionDirectory);
std::string unixSearchPath = convertPathFormatToUnixStyle(searchPath); return FileUtils::getPathForFilename(unixFileName, unixResolutionDirectory, unixSearchPath);
} std::string FileUtilsWin32::getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename)
{
std::string unixDirectory = convertPathFormatToUnixStyle(strDirectory);
std::string unixFilename = convertPathFormatToUnixStyle(strFilename); return FileUtils::getFullPathForDirectoryAndFilename(unixDirectory, unixFilename);
} string FileUtilsWin32::getWritablePath() const
{
// Get full path of executable, e.g. c:\Program Files (x86)\My Game Folder\MyGame.exe
char full_path[CC_MAX_PATH + ];
::GetModuleFileNameA(nullptr, full_path, CC_MAX_PATH + ); // Debug app uses executable directory; Non-debug app uses local app data directory
//#ifndef _DEBUG
// Get filename of executable only, e.g. MyGame.exe
char *base_name = strrchr(full_path, '\\'); if(base_name)
{
char app_data_path[CC_MAX_PATH + ]; // Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data
if (SUCCEEDED(SHGetFolderPathA(nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, app_data_path)))
{
string ret((char*)app_data_path); // Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame.exe
ret += base_name; // Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame
ret = ret.substr(, ret.rfind(".")); ret += "\\"; // Create directory
if (SUCCEEDED(SHCreateDirectoryExA(nullptr, ret.c_str(), nullptr)))
{
return convertPathFormatToUnixStyle(ret);
}
}
}
//#endif // not defined _DEBUG // If fetching of local app data directory fails, use the executable one
string ret((char*)full_path); // remove xxx.exe
ret = ret.substr(, ret.rfind("\\") + ); ret = convertPathFormatToUnixStyle(ret); return ret;
} NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32

当我们使用cc.FileUtils:getInstance():getStringFromFile()读取文件内容的时候就获取到的是解密后的内容了,这个解密的过程是在引擎层面做好的了,也可以说对使用者来说是透明的.这样也是契合了为什么在前一篇文章中我为什么会说我坚持使用这个接口作为配置文件读取的主要原因.同样,如果是加密图片,plist文件,只需要按照一般我们使用过的方式使用就好了,不需要做任何的改动.

加密工具可以去下载一份quick的源码,里面有提供一个pack_files.bat脚本,用它来打包就好了,然后在引擎启动的时候设置好我们的签名,如下:

 bool AppDelegate::applicationDidFinishLaunching()
{
auto engine = LuaEngine::getInstance();
ScriptEngineManager::getInstance()->setScriptEngine(engine);
lua_State* L = engine->getLuaStack()->getLuaState();
lua_module_register(L); cocos2d::FileUtils::getInstance()->setPopupNotify(false); FWResEncrypt::getInstance()->setXXTeaKeyAndSign("RESPAWN", strlen("RESPAWN"), "FW", strlen("FW"));
engine->getLuaStack()->setXXTEAKeyAndSign("RESPAWN", strlen("RESPAWN"), "FW", strlen("FW")); // If you want to use Quick-Cocos2d-X, please uncomment below code
// register_all_quick_manual(L);
if (engine->executeScriptFile("src/main.lua")) {
return false;
} return true;
}

好吧,到这里就结束了.下一篇文章考虑可能会做一下增量动态更新,敬请期待.欢迎交流.我好久没用我的github了,待我稍微整理一下,然后以合适的方式上传我的代码,开源给大家.另外,我现在在找相关游戏资源,期望是整套的网游资源,要不然我也就只能做做这些架构方面的事情了,涉及不到游戏的业务逻辑.