`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了,待我稍微整理一下,然后以合适的方式上传我的代码,开源给大家.另外,我现在在找相关游戏资源,期望是整套的网游资源,要不然我也就只能做做这些架构方面的事情了,涉及不到游戏的业务逻辑.
`cocos2dx非完整` 添加xxtea加密模块的更多相关文章
- `cocos2dx非完整` 游戏架构缩影 添加启动流程
这期的话题可能不是很好, 我没有想到很好的词句去更好的表达. 我一直都是很固执的认为, 同一类型的游戏,在开发做的前期工作上面其实都是可以复用的,也就是大同小异的.从游戏启动,启动日志,启动检查,检查 ...
- `cocos2dx 非完整` UI解析模块
昨天在cocos2dx的一个群里,遇到一位匿名为x的朋友询问的问题,是关于ui的.他使用c++写了不少的ui封装节点,用来实现游戏中的各种不同效果.然后现在想改用lua,于是尝试使用最小代价去复用自己 ...
- `cocos2dx非完整` 日志模块 增量更新
在上一篇文章中,说到了"流程"的由来,以及我对流程的使用. 这一片就是对流程的应用.前一篇文章中说到了三条流程 check_log_measure, check_env_measu ...
- `cocos2dx非完整` 开始自己的FW模块
上一篇的文章中说到了一些个人习惯的东西以及一些简单的项目配置,这一篇文章我们来进一步完善一些东西.首先,打开编译以后的客户端执行,会看到一大堆的fileutils加载luac文件的提示,在终端显示一大 ...
- `cocos2dx非完整`开篇
相信每个人都有一些自己的项目开发习惯,在·开篇·中我主要是会提到一些项目的配置问题.无论做一款什么样的手游项目,我们总是会从需求的角度出发去选择开发引擎,开发工具等一些列的工具去完善我们的开发环境.当 ...
- 新版本ffmpeg解码非完整H264帧失败
按照ffmpeg/doc/examples/decoding_encoding.c中video_decode_example解码H264,新版本ffmpeg解码非完整H264帧,定量读取数据直接给av ...
- `fw服务端非完整` 工程开发初期的工作
前面写到了一些关于cocos2dx在开发中的一些模块以及一些解决方法,那些都属于本人的个人简介和个人倾向的解决方案.最近这几天我完善了一下ui解析的部分,当然也只是抽出一点点时间去做的这件事情.我添加 ...
- MFC非模态添加进程控件方法二(自定义消息方法)
以下内容有大部分转载自CSDN,经过自己整理完成. 该文主要的方法为在非模态对话框中自定义一组消息函数,然后在主窗口中开辟一个线程通过线程把消息传递给子窗口进行更新. 在子窗口类中定义消息如下: /* ...
- MFC非模态添加进程控件方法一(线程方法)
由于非模态对话框的自己没有消息循环,创建后无法进行消息处理.需要和父窗口共用消息循环.如果单独在子窗口进行控件由于自己没有单独的消息循环,更新是无法进行的. 如果在父窗口更新控件会造成程序假死.如以下 ...
随机推荐
- paip.信用卡账单处理系统功能vO22
paip.信用卡账单处理系统功能vO22 作者Attilax 艾龙, EMAIL:1466519819@qq.com 来源:attilax的专栏 地址:http://blog.csdn.net/att ...
- android: SharedPreferences实现记住密码功能
既然是实现记住密码的功能,那么我们就不需要从头去写了,因为在上一章中的最佳实 践部分已经编写过一个登录界面了,有可以重用的代码为什么不用呢?那就首先打开 BroadcastBestPractice 项 ...
- malloc钩子和内存泄漏工具mtrace、Valgrind
一:malloc钩子函数 static void* (* old_malloc_hook) (size_t,const void *);static void (* old_free_hook)(vo ...
- AutoCAD2007专业版
07版的AutoCAD应该是一个很经典的版本了,点此下载,附带破解注册机和天正的插件包,可以查看天正软件画的图纸. AutoCAD2007本身没有标签工具,切换窗口很不方便,如果能配合多标签插件Doc ...
- arcgis打开图层后右下角坐标小数点位数调整
打开arcmap,加载图层后,在其右下方会显示鼠标移动的点坐标,但是默认显示的小数点只有三位,如果是经纬度坐标,只有三位的话不够精确,因此想着能否改变其显示的精度,搜了半天,算是搜到了,但是过了一段时 ...
- TCP_NODELAY 和 TCP_CORK主要区别
一句话总结: tcp_nodelay:禁止nagle算法,有需要发送的就立即发送,比较常见 tcp_cork:它是一种加强的nagle算法,过程和nagle算法类似,都是累计数据然后发送.但它没有 n ...
- S7-200系列PLC与WINCC以太网通信CP243i的实例
S7-200系列PLC与WINCC以太网通信CP243i的实例 ----选用大连德嘉国际电子www.dl-winbest.cn的CP243i作为连接S7-200的PPI口转以太网RJ45的接口转换器. ...
- Javascript 严格模式
简介 严格模式是一种将更好的错误检查引入代码中的方法. 在使用严格模式时,你无法使用隐式声明的变量.将值赋给只读属性或将属性添加到不可扩展的对象等. 声明严格模式 可以通过在文件.程序或函数的开头添加 ...
- zookeeper节点Watch机制实例展示
znode以某种方式发生变化时,“观察”(watch)机制可以让客户端得到通知.可以针对ZooKeeper服务的“操作”来设置观察,该服务的其他 操作可以触发观察. 实现Watcher,复写proce ...
- Android Studio 中关于NDK编译及jni header生成的问题
之前由于工作原因使用grails这个基于groovy的框架做项目,对groovy感觉很好. 基于groovy的gradle构建系统对我而言自然也是好的没得说. Android Studio 正式版出来 ...