cocos2dx使用xxtea加密资源

时间:2022-10-01 21:48:33

记录在cocos2dx下使用xxtea加密,以下都为ios版本操作

1.资源加密

quick有一个加密资源和脚本的解决方案,即使用xxtea加密并且可以进行打包,在pack_files文件夹下有一个pack_files.sh本人使用的mac,中windows中使用.bat

脚本命令的详细讲解,在这里只是使用了对资源进行加密,不进行打包。脚本命令如下

./pack_files.sh -i ./res -o ./resnew -ek key -es sign
1.资源读取

解密涉及到对cocos2dx引擎的一些改动,所以写了个ResourcesDecode类,cocos2dx本身含有xxtea类文件,把这2个类文件放入到项目cocos2d/cocos/platform下,在cocos2d.h文件夹中加入2个类的引用,在cocos2d/build目录下把2个类加入到ios的静态类库中,在AppDelegate.cpp场景切换之前加入

ResourcesDecode::getInstance()->setXXTEAKeyAndSign("key", "sign");
具体的方法会在 ResourcesDecode中介绍,会上传文件。

修改image.h中Image::initWithImageFile方法中做如下更改

Data data = ResourcesDecode::getInstance()->decodeData(path.c_str());
ios平台文件中的 apple/CCFileUtils中修改FileUtilsApple::getValueMapFromFile中做如下更改

Data data = ResourcesDecode::getInstance()->decodeData(fullPath.c_str());
ssize_t bufferSize = data.getSize();
unsigned char* pFileData = data.getBytes();
NSData *nsdata = [[[NSData alloc] initWithBytes:pFileData length:bufferSize] autorelease];

NSPropertyListFormat format;
NSString *error;
NSMutableDictionary *dict = (NSMutableDictionary *)[
NSPropertyListSerialization propertyListFromData:nsdata
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&error];
//over

读取json文件还需在FileUtils::getStringFromFile中做如下更改

Data data = ResourcesDecode::getInstance()->decodeData(path.c_str());
读取tilemap文件在SAXParser::parse下做如下更改

Data data = ResourcesDecode::getInstance()->decodeData(path.c_str());

上面的decodeData到底做了什么操作呢,其实就是读取到资源再对它解密操作

Data ResourcesDecode::decodeData(const char *fileName)
{
Data ret;
ssize_t dsize = 0;
unsigned char* dresult;
unsigned char* buffer = nullptr;
size_t size = 0;
size_t readsize;
auto fileutils = FileUtils::getInstance();
do
{
// Read the file from hardware
std::string fullPath = fileutils->fullPathForFilename(fileName);
FILE *fp = fopen(fullPath.c_str(), "rb");
CC_BREAK_IF(!fp);
fseek(fp,0,SEEK_END);
size = ftell(fp);
fseek(fp,0,SEEK_SET);

buffer = (unsigned char*)malloc(sizeof(unsigned char) * size);
readsize = fread(buffer, sizeof(unsigned char), size, fp);
fclose(fp);

} while (0);

if (nullptr == buffer || 0 == readsize)
{
CCLOG("Get data from file %s failed", fileName);
}
if (_xxteaEnabled && strncmp((char*)buffer, _xxteaSign, _xxteaSignLen) == 0)
{
// decrypt XXTEA
xxtea_long len = 0;
dresult = xxtea_decrypt(buffer + _xxteaSignLen,
(xxtea_long)readsize - _xxteaSignLen,
(unsigned char*)_xxteaKey,
(xxtea_long)_xxteaKeyLen,
&len);
dsize = len;
ret.fastSet(dresult, dsize);
}
if (buffer) {
free(buffer);
}
return ret;
}

可以参考 FileUtils ::getFileData中的处理。