一、前言

1.我将要给大家分享的是XXTEA加密方式,对图片资源进行加密。
2.需要工具:quick-lua中已经集成图片加密工具,但是我没有用quick,所以单独把这个加密文件夹拎出来了。点击下载加密工具。
http://pan.baidu.com/s/1pLyI6NL

二、修改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 *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,SEEK_END);
        size = ftell(fp);
        fseek(fp,SEEK_SET);
        
        if (forString)
        {
            buffer = (unsigned char*)malloc(sizeof(unsigned char) * (size + 1));
            buffer[size] = '\0';
        }
        else
        {
            buffer = (unsigned char*)malloc(sizeof(unsigned char) * size);
        }
        
        readsize = fread(buffer,sizeof(unsigned char),size,fp);
        fclose(fp);
        
        if (forString && readsize < size)
        {
            buffer[readsize] = '\0';
        }
    } while (0);
    
    if (nullptr == buffer || 0 == readsize)
    {
        std::string msg = "Get data from file(";
        msg.append(filename).append(") Failed!");
        cclOG("%s",msg.c_str());
    }
    else
    {
        //ret.fastSet(buffer,readsize);
       	//======新的改动
        unsigned long newSize = 0;
		unsigned char *newBuffer = FileUtils::decryptBuffer(buffer,readsize,&newSize);
		ret.fastSet(newBuffer,newSize);
    }


4.在上面那个文件中:frameworks\cocos2d-x\cocos\platform\CCFileUtils.cpp,修改getFileData函数:
unsigned char* FileUtils::getFileData(const std::string& filename,const char* mode,ssize_t *size)
{
    unsigned char * buffer = nullptr;
    CCASSERT(!filename.empty() && size != nullptr && mode != nullptr,"Invalid parameters.");
    *size = 0;
    do
    {
        // read the file from hardware
        const std::string fullPath = fullPathForFilename(filename);
        FILE *fp = fopen(fullPath.c_str(),mode);
        CC_BREAK_IF(!fp);
        
        fseek(fp,SEEK_END);
        *size = ftell(fp);
        fseek(fp,SEEK_SET);
        buffer = (unsigned char*)malloc(*size);
        *size = fread(buffer,*size,fp);
        fclose(fp);
    } while (0);
    
    if (!buffer)
    {
        std::string msg = "Get data from file(";
        msg.append(filename).append(") Failed!");
        
        cclOG("%s",msg.c_str());
    }else{
    		//新的改动=========
			unsigned long newSize = 0;
			unsigned char *newBuffer = FileUtils::decryptBuffer(buffer,&newSize);
			*size = newSize;
			buffer = newBuffer;
	}
    return buffer;
}

三、修改CCFileUtils-win32.cpp文件

1.找到 frameworks\cocos2d-x\cocos\platform\win32\ 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 = 0;
    do
    {
        // read the file from hardware
        std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename);

        WCHAR wszBuf[CC_MAX_PATH] = {0};
        MultiBytetoWideChar(CP_UTF8,fullPath.c_str(),-1,wszBuf,sizeof(wszBuf)/sizeof(wszBuf[0]));

        HANDLE fileHandle = ::CreateFileW(wszBuf,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,nullptr);
        CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE);
        
        size = ::GetFileSize(fileHandle,nullptr);

        if (forString)
        {
            buffer = (unsigned char*) malloc(size + 1);
            buffer[size] = '\0';
        }
        else
        {
            buffer = (unsigned char*) malloc(size);
        }
        DWORD sizeRead = 0;
        BOOL successed = FALSE;
        successed = ::ReadFile(fileHandle,buffer,&sizeRead,nullptr);
        ::CloseHandle(fileHandle);

        if (!successed)
        {
            // should determine buffer value,or it will cause memory leak
            if (buffer)
            {
                free(buffer);
                buffer = nullptr;
            }    
        }
    } while (0);
    
    Data ret;

    if (buffer == nullptr || size == 0)
    {
        std::string msg = "Get data from file(";
        // Gets error code.
        DWORD errorCode = ::GetLastError();
        char errorCodeBuffer[20] = {0};
        snprintf(errorCodeBuffer,sizeof(errorCodeBuffer),"%d",errorCode);

        msg = msg + filename + ") Failed,error code is " + errorCodeBuffer;
        cclOG("%s",msg.c_str());

        if (buffer)
            free(buffer);
    }
    else
    {
    	//新的改动
        unsigned long newSize = 0;
		unsigned char *newBuffer = FileUtils::decryptBuffer(buffer,&newSize);
        //ret.fastSet(buffer,size);
		ret.fastSet(newBuffer,newSize);
    }
    return ret;
}

unsigned char* FileUtilsWin32::getFileData(const std::string& filename,ssize_t* size)
{
    unsigned char * pBuffer = nullptr;
    *size = 0;
    do
    {
        // read the file from hardware
        std::string fullPath = fullPathForFilename(filename);

        WCHAR wszBuf[CC_MAX_PATH] = {0};
        MultiBytetoWideChar(CP_UTF8,nullptr);
        CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE);
        
        *size = ::GetFileSize(fileHandle,nullptr);

        pBuffer = (unsigned char*) malloc(*size);
        DWORD sizeRead = 0;
        BOOL successed = FALSE;
        successed = ::ReadFile(fileHandle,pBuffer,nullptr);
        ::CloseHandle(fileHandle);

        if (!successed)
        {
            free(pBuffer);
            pBuffer = nullptr;
        }
    } while (0);
    
    if (! pBuffer)
    {
        std::string msg = "Get data from file(";
        // Gets error code.
        DWORD errorCode = ::GetLastError();
        char errorCodeBuffer[20] = {0};
        snprintf(errorCodeBuffer,msg.c_str());
    }else{
		//新的改动
		unsigned long newSize = 0;
		unsigned char *newBuffer = FileUtils::decryptBuffer(pBuffer,&newSize);
		*size = newSize;
		pBuffer = newBuffer;
	}
    return pBuffer;
}

四、修改CCFileUtils-android.cpp文件

1.找到 frameworks\cocos2d-x\cocos\platform\android\ CCFileUtils-android.cpp,添加对应的代码:
Data FileUtilsAndroid::getData(const std::string& filename,bool forString)
{
    if (filename.empty())
    {
        return Data::Null;
    }
    
    unsigned char* data = nullptr;
    ssize_t size = 0;
    string fullPath = fullPathForFilename(filename);
    cocosplay::updateAssets(fullPath);

    if (fullPath[0] != '/')
    {
        string relativePath = string();

        size_t position = fullPath.find("assets/");
        if (0 == position) {
            // "assets/" is at the beginning of the path and we don't want it
            relativePath += fullPath.substr(strlen("assets/"));
        } else {
            relativePath += fullPath;
        }
        cclOGINFO("relative path = %s",relativePath.c_str());

        if (nullptr == FileUtilsAndroid::assetmanager) {
            LOGD("... FileUtilsAndroid::assetmanager is nullptr");
            return Data::Null;
        }

        // read asset data
        AAsset* asset =
            AAssetManager_open(FileUtilsAndroid::assetmanager,relativePath.c_str(),AASSET_MODE_UNKNowN);
        if (nullptr == asset) {
            LOGD("asset is nullptr");
            return Data::Null;
        }

        off_t fileSize = AAsset_getLength(asset);

        if (forString)
        {
            data = (unsigned char*) malloc(fileSize + 1);
            data[fileSize] = '\0';
        }
        else
        {
            data = (unsigned char*) malloc(fileSize);
        }

        int bytesread = AAsset_read(asset,(void*)data,fileSize);
        size = bytesread;

        AAsset_close(asset);
    }
    else
    {
        do
        {
            // read rrom other path than user set it
            //cclOG("GETTING FILE ABSOLUTE DATA: %s",filename);
            const char* mode = nullptr;
            if (forString)
                mode = "rt";
            else
                mode = "rb";

            FILE *fp = fopen(fullPath.c_str(),mode);
            CC_BREAK_IF(!fp);
            
            long fileSize;
            fseek(fp,SEEK_END);
            fileSize = ftell(fp);
            fseek(fp,SEEK_SET);
            if (forString)
            {
                data = (unsigned char*) malloc(fileSize + 1);
                data[fileSize] = '\0';
            }
            else
            {
                data = (unsigned char*) malloc(fileSize);
            }
            fileSize = fread(data,fileSize,fp);
            fclose(fp);
            
            size = fileSize;
        } while (0);
    }
    
    Data ret;
    if (data == nullptr || size == 0)
    {
        std::string msg = "Get data from file(";
        msg.append(filename).append(") Failed!");
        cclOG("%s",msg.c_str());
    }
    else
    {
    	//新的改动==========
        unsigned long newSize = 0;
		unsigned char *newBuffer = FileUtils::decryptBuffer(data,&newSize);
        // ret.fastSet(data,newSize);
        cocosplay::notifyFileLoaded(fullPath);
    }

    return ret;
}


unsigned char* FileUtilsAndroid::getFileData(const std::string& filename,ssize_t * size)
{    
    unsigned char * data = 0;
    
    if ( filename.empty() || (! mode) )
    {
        return 0;
    }
    
    string fullPath = fullPathForFilename(filename);
    cocosplay::updateAssets(fullPath);

    if (fullPath[0] != '/')
    {
        string relativePath = string();

        size_t position = fullPath.find("assets/");
        if (0 == position) {
            // "assets/" is at the beginning of the path and we don't want it
            relativePath += fullPath.substr(strlen("assets/"));
        } else {
            relativePath += fullPath;
        }
        LOGD("relative path = %s",relativePath.c_str());

        if (nullptr == FileUtilsAndroid::assetmanager) {
            LOGD("... FileUtilsAndroid::assetmanager is nullptr");
            return nullptr;
        }

        // read asset data
        AAsset* asset =
            AAssetManager_open(FileUtilsAndroid::assetmanager,AASSET_MODE_UNKNowN);
        if (nullptr == asset) {
            LOGD("asset is nullptr");
            return nullptr;
        }

        off_t fileSize = AAsset_getLength(asset);

        data = (unsigned char*) malloc(fileSize);

        int bytesread = AAsset_read(asset,fileSize);
        if (size)
        {
            *size = bytesread;
        }

        AAsset_close(asset);
    }
    else
    {
        do
        {
            // read rrom other path than user set it
            //cclOG("GETTING FILE ABSOLUTE DATA: %s",filename);
            FILE *fp = fopen(fullPath.c_str(),SEEK_SET);
            data = (unsigned char*) malloc(fileSize);
            fileSize = fread(data,fp);
            fclose(fp);
            
            if (size)
            {
                *size = fileSize;
            }
        } while (0);
    }
    
    if (! data)
    {
        std::string msg = "Get data from file(";
        msg.append(filename).append(") Failed!");
        cclOG("%s",msg.c_str());
    }
    else
    {
    	//新的改动
		unsigned long newSize = 0;
		unsigned char *newBuffer = FileUtils::decryptBuffer(data,&newSize);
		*size = newSize;
		data = newBuffer;

        cocosplay::notifyFileLoaded(fullPath);
    }

    return data;
}

五、修改CCFileUtils-apple.mm文件

1.找到 frameworks\cocos2d-x\cocos\platform\apple\ CCFileUtils-apple.cpp,修改对应的代码:getValueMapFromFile。以便读取plist文件,是因为ios读取plist文件方式和android和win32不同。
ValueMap FileUtilsApple::getValueMapFromFile(const std::string& filename)
{
	//====新的改动
    std::string fullPath = fullPathForFilename(filename);
    Data d = FileUtils::getDataFromFile(filename);
    unsigned long fileSize = d.getSize();
    unsigned char* pFileData = d.getBytes();
    NSData *data = [[[NSData alloc] initWithBytes:pFileData length:fileSize] autorelease];
    nspropertyListFormat format;
    Nsstring *error;
    NSMutableDictionary *dict = (NSMutableDictionary *)[
                                                         nspropertyListSerialization propertyListFromData:data
                                                         mutabilityOption:nspropertyListMutableContainersAndLeaves
                                                         format:&format
                                                         errorDescription:&error];
    //====改动结束
    
    //std::string fullPath = fullPathForFilename(filename);
    //Nsstring* path = [Nsstring stringWithUTF8String:fullPath.c_str()];
    //NSDictionary* dict = [NSDictionary dictionaryWithContentsOfFile:path];

    ValueMap ret;

    if (dict != nil)
    {
        for (id key in [dict allKeys])
        {
            id value = [dict objectForKey:key];
            addValuetoDict(key,value,ret);
        }
    }
    return ret;
}


六、大功告成!

1.重新编译c++代码,把res文件夹替换成加密后的文件夹,即可正常运行。
2.注意key和sign要和你的AppDelegate中设置的key和sign一样:
LuaStack* stack = LuaEngine::getInstance()->getLuaStack();
stack->setXXTEAKeyAndSign(key,strlen(key),sign,strlen(sign));

cocos2dx-lua 3.4 之 图片资源加密!的更多相关文章

  1. ios – 如何使用blender和PowerVR SDK为cocos3d创建一个简单的3d球体

    我是cocos3d的新手.我想创建一个简单的项目–旋转的3d球体.我用搅拌机设计了一个3d球体.所以我想要帮助创建collada文件和pod文件.使用blender和PowerVRSDK创建这个简单的3d对象时应该注意什么.谢谢解决方法如何在搅拌机中制作简单的球体,然后使用JeffLamarche的Blender-to-iOSscript将其导出?这甚至不需要Cocos或PowerVR,但这是一个良好的开端.由于您可以在iOS中轻松地将Cocos与非Cocos类集成,因此可能会有所帮助.你可以更进一步,利

  2. CocosCreator骨骼动画之龙骨DragonBones

    这篇文章主要介绍了怎么在CocosCreator中使用骨骼动画龙骨DragonBones,对骨骼动画感兴趣的同学,可以试一下

  3. 如何使用CocosCreator对象池

    这篇文章主要介绍了CocosCreator对象池,对性能有研究的同学,要着重看一下

  4. 整理CocosCreator常用知识点

    这篇文章主要介绍了整理CocosCreator常用知识点,这些知识点,平时几乎都能用到,希望同学们看完后,可以自己去试一下,加深印象

  5. 详解CocosCreator MVC架构

    这篇文章主要介绍了CocosCreator MVC架构,同学们在制作游戏过程中,尽量使用一些架构,会避免很多问题

  6. 游戏开发中如何使用CocosCreator进行音效处理

    这篇文章主要介绍了游戏开发中如何使用CocosCreator进行音效处理,并对音效组件进行封装,方便以后使用,同学们看完之后,一定要亲手实验一下

  7. CocosCreator如何实现划过的位置显示纹理

    这篇文章主要介绍了CocosCreator纹理shader的一些知识,想了解shader的同学,一定要看下,并且亲自动手实践

  8. 详解CocosCreator华容道数字拼盘

    这篇文章主要介绍了详解CocosCreator华容道数字拼盘,对华容道感兴趣的同学,看完之后,可以回去亲手试一下

  9. Android实战之Cocos游戏容器搭建

    这篇文章主要介绍了Android实战之Cocos游戏容器搭建,文章围绕主题展开详细的内容介绍,具有一定的参考价值,感兴趣的小伙伴可以参考一下

  10. 详解CocosCreator系统事件是怎么产生及触发的

    这篇文章主要介绍了CocosCreator系统事件是怎么产生及触发的,虽然内容不少,但是只要一点点抽丝剥茧,具体分析其内容,就会豁然开朗

随机推荐

  1. 【cocos2d-x 3.x 学习笔记】对象内存管理

    Cocos2d-x的内存管理cocos2d-x中使用的是上面的引用计数来管理内存,但是又增加了一些自己的特色。cocos2d-x中通过Ref类来实现引用计数,所有需要实现内存自动回收的类都应该继承自Ref类。下面是Ref类的定义:在cocos2d-x中创建对象通常有两种方式:这两中方式的差异可以参见我另一篇博文“对象创建方式讨论”。在cocos2d-x中提倡使用第二种方式,为了避免误用第一种方式,一般将构造函数设为protected或private。参考资料:[1]cocos2d-x高级开发教程2.3节[

  2. 利用cocos2dx 3.2开发消灭星星六如何在cocos2dx中显示中文

    由于编码的不同,在cocos2dx中的Label控件中如果放入中文字,往往会出现乱码。为了方便使用,我把这个从文档中获取中文字的方法放在一个头文件里面Chinese.h这里的tex_vec是cocos2dx提供的一个保存文档内容的一个容器。这里给出ChineseWords,xml的格式再看看ChineseWord的实现Chinese.cpp就这样,以后在需要用到中文字的地方,就先include这个头文件然后调用ChineseWord函数,获取一串中文字符串。

  3. 利用cocos2dx 3.2开发消灭星星七关于星星的算法

    在前面,我们已经在GameLayer中利用随机数初始化了一个StarMatrix,如果还不知道怎么创建星星矩阵请回去看看而且我们也讲了整个游戏的触摸事件的派发了。

  4. cocos2dx3.x 新手打包APK注意事项!

    这个在编译的时候就可以发现了比较好弄这只是我遇到的,其他的以后遇到再补充吧。。。以前被这两个问题坑了好久

  5. 利用cocos2dx 3.2开发消灭星星八游戏的结束判断与数据控制

    如果你看完之前的,那么你基本已经拥有一个消灭星星游戏的雏形。开始把剩下的两两互不相连的星星消去。那么如何判断是GameOver还是进入下一关呢。。其实游戏数据贯穿整个游戏,包括星星消除的时候要加到获得分数上,消去剩下两两不相连的星星的时候的加分政策等,因此如果前面没有做这一块的,最好回去搞一搞。

  6. 利用cocos2dx 3.2开发消灭星星九为游戏添加一些特效

    needClear是一个flag,当游戏判断不能再继续后,这个flag变为true,开始消除剩下的星星clearSumTime是一个累加器ONE_CLEAR_TIME就是每颗星星消除的时间2.连击加分信息一般消除一次星星都会有连击信息和加多少分的信息。其实这些combo标签就是一张图片,也是通过控制其属性或者runAction来实现。源码ComboEffect.hComboEffect.cpp4.消除星星粒子效果消除星星时,为了实现星星爆裂散落的效果,使用了cocos2d提供的粒子特效引擎对于粒子特效不了

  7. 02 Cocos2D-x引擎win7环境搭建及创建项目

    官网有搭建的文章,直接转载记录。环境搭建:本文介绍如何搭建Cocos2d-x3.2版本的开发环境。项目创建:一、通过命令创建项目前面搭建好环境后,怎样创建自己的Cocos2d-x项目呢?先来看看Cocos2d-x3.2的目录吧这就是Cocos2d-x3.2的目录。输入cocosnew项目名–p包名–lcpp–d路径回车就创建成功了例如:成功后,找到这个项目打开proj.win32目录下的Hello.slnF5成功了。

  8. 利用cocos2dx 3.2开发消灭星星十为游戏添加音效项目源码分享

    一个游戏,声音也是非常的重要,其实cocos2dx里面的简单音效引擎的使用是非常简单的。我这里只不过是用一个类对所有的音效进行管理罢了。Audio.hAudio.cpp好了,本系列教程到此结束,第一次写教程如有不对请见谅或指教,谢谢大家。最后附上整个项目的源代码点击打开链接

  9. 03 Helloworld

    程序都有一个入口点,在C++就是main函数了,打开main.cpp,代码如下:123456789101112131415161718#include"main.h"#include"AppDelegate.h"#include"cocos2d.h"USING_NS_CC;intAPIENTRY_tWinMain{UNREFERENCED_ParaMETER;UNREFERENCED_ParaMETER;//createtheapplicationinstanceAppDelegateapp;return

  10. MenuItemImage*图标菜单创建注意事项

    学习cocos2dx,看的是cocos2d-x3.x手游开发实例详解,这本书错误一大把,本着探索求知勇于发现错误改正错误的精神,我跟着书上的例子一起调试,当学习到场景切换这个小节的时候,出了个错误,卡了我好几个小时。

返回
顶部