一、前言
1.我将要给大家分享的是XXTEA加密方式,对图片资源进行加密。
2.需要工具:quick-lua中已经集成图片加密工具,但是我没有用quick,所以单独把这个加密文件夹拎出来了。点击下载加密工具。
二、修改CCFileUtils.h和cpp文件
1.找到frameworks\cocos2d-x\cocos\platform\CCFileUtils.h,添加一个结构体ResEncryptData:
class CC_DLL FileUtils
{
public:
//=====添加代码
static struct ResEncryptData{
ResEncryptData(){
allowNoEncrpt = true;
key = "key123456";
sign = "sign520";
}
std::string key;
std::string sign;
bool allowNoEncrpt;
}encryptData;
static unsigned char* decryptBuffer(unsigned char* buf, unsigned long size, unsigned long *newSize);
//=====添加结束
/**
* Gets the instance of FileUtils.
*/
static FileUtils* getInstance();
/**
* Destroys the instance of FileUtils.
*/
static void destroyInstance();
2.
找到
frameworks\cocos2d-x\cocos\platform\
CCFileUtils.cpp,添加对应的实现代码:
//头文件声明=====
#include "xxtea/xxtea.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include "xxtea/xxtea.cpp"
#endif
unsigned char* FileUtils::decryptBuffer(unsigned char* buf, unsigned long size, unsigned long *newSize){
unsigned char *m_xxteaKey = (unsigned char *)FileUtils::encryptData.key.c_str();
unsigned char *m_xxteaSign = (unsigned char *)FileUtils::encryptData.sign.c_str();
xxtea_long m_xxteaSignLen = FileUtils::encryptData.sign.length();
xxtea_long m_xxteaKeyLen = FileUtils::encryptData.key.length();
if (NULL==buf) return NULL;
unsigned char* buffer = NULL;
bool isXXTEA = true;
for (unsigned int i = 0; isXXTEA && i < m_xxteaSignLen && i < size; ++i)
{
if(buf[i] != m_xxteaSign[i]){
isXXTEA = false;
break;
}
}
if(m_xxteaSignLen == 0){
isXXTEA = false;
}
if (isXXTEA)
{
// decrypt XXTEA
xxtea_long len = 0;
buffer = xxtea_decrypt(buf + m_xxteaSignLen,
(xxtea_long)size - (xxtea_long)m_xxteaSignLen,
(unsigned char*)m_xxteaKey,
(xxtea_long)m_xxteaKeyLen,
&len);
delete []buf;
buf = NULL;
size = len;
}
else
{
if(FileUtils::getInstance()->encryptData.allowNoEncrpt)
{buffer = buf;}
}
*newSize = size;
return buffer;
}
3.在上面那个文件中: frameworks\cocos2d-x\cocos\platform\ CCFileUtils.cpp,修改getData函数:
static Data getData(const std::string& filename, bool forString)
{
if (filename.empty())
{
return Data::Null;
}
Data ret;
unsigned char* buffer = nullptr;
size_t size = 0;
size_t readsize;
const char* mode = nullptr;
if (forString)
mode = "rt";
else
mode = "rb";
do
{
// Read the file from hardware
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename);
FILE *fp = fopen(fullPath.c_str(), mode);
CC_BREAK_IF(!fp);
fseek(fp,0,SEEK_END);
size = ftell(fp);
fseek(fp,0,SEEK_SET);
if (forString)
{
buffe