cocos2dx使用xxtea加密資源
阿新 • • 發佈:2019-02-13
記錄在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
解密涉及到對cocos2dx引擎的一些改動,所以寫了個ResourcesDecode類,cocos2dx本身含有xxtea類檔案,把這2個
- ResourcesDecode::getInstance()->setXXTEAKeyAndSign("key", "sign");
修改image.h中Image::initWithImageFile方法中做如下更改
-
Data data = ResourcesDecode::getInstance()->decodeData(path.c_str());
- 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());
- Data data = ResourcesDecode::getInstance()->decodeData(path.c_str());
上面的decodeData到底做了什麼操作呢,其實就是讀取到資源再對它解密操作
- Data ResourcesDecode::decodeData(constchar *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中的處理。