cocos2dx lua XXTEA来加密解密实现详解

时间:2021-01-20 21:47:43
cocos2dx lua已经集成了对lua脚本的加解密,见AppDelegate.cpp
  1.     LuaStack* stack = engine->getLuaStack();
  2.     stack->setXXTEAKeyAndSign("123", strlen("123"), "cloud", strlen("cloud"));
复制代码

它是通过XXTEA来加解密的。参数,key,keyLen,signment,signmentLen。它的签名作用可能是用来判断文件是否经过加密的。
       好,我们来对文件加密。打开cocos2d-x\external\xxtea文件夹,调用相关函数xxtea_encrypt进行加密,最后在文件开始位置,写上签名就可以了。我把相关操作封装成一个python文件。可以直接调用。
  1. import xxteaModule
  2. import os

  3. def ReadFile(filePath):
  4.     file_object = open(filePath,'rb')
  5.     all_the_text = file_object.read()
  6.     file_object.close()
  7.     return all_the_text

  8. def WriteFile(filePath,all_the_text):    
  9.     file_object = open(filePath,'wb')    
  10.     file_object.write(all_the_text)
  11.     file_object.close()
  12.     
  13. def BakFile(filePath,all_the_text):
  14.     file_bak = filePath[:len(filePath)-3] + 'bak'   
  15.     WriteFile(file_bak,all_the_text)



  16. def ListLua(path):
  17.     fileList = [] 
  18.     for root,dirs,files in os.walk(path):
  19.        for eachfiles in files:
  20.            if eachfiles[-4:] == '.lua' :               
  21.                fileList.append(root + '/' + eachfiles)
  22.     return fileList

  23. def EncodeWithXxteaModule(filePath,key,signment):    
  24.     all_the_text = ReadFile(filePath)    

  25.     if all_the_text[:len(signment)] == signment :
  26.         return
  27.     #bak lua
  28.     BakFile(filePath,all_the_text)
  29.        
  30.     encrypt = xxteaModule.encrypt(all_the_text,key)
  31.     signment = signment + encrypt
  32.     WriteFile(filePath,signment)    
  33.     
  34. def EncodeLua(projectPath,key,signment):
  35.     path = projectPath + '/src'
  36.     fileList = ListLua(path)
  37.     for files in fileList:
  38.         EncodeWithXxteaModule(files,key,signment)

  39. def FixCpp(projectPath,key,signment):
  40.     filePath = projectPath + '/frameworks/runtime-src/Classes/AppDelegate.cpp'
  41.     all_the_text = ReadFile(filePath)

  42.     #bak cpp
  43.     BakFile(filePath,all_the_text)    


  44.     pos = all_the_text.find('stack->setXXTEAKeyAndSign')
  45.     left = all_the_text.find('(',pos)
  46.     right = all_the_text.find(';',pos)   

  47.     word = str.format('("%s", strlen("%s"), "%s", strlen("%s"))' % (key,key,signment,signment))
  48.     
  49.     all_the_text = all_the_text[:left] + word + all_the_text[right:-1]
  50.     
  51.     WriteFile(filePath,all_the_text) 
  52.     
  53.     
  54.     
  55. projectPath = "D:/cocosIDEWork/aseGame/"
  56. key = "123"
  57. signment = "cloud"


  58. EncodeLua(projectPath,key,signment)
  59. FixCpp(projectPath,key,signment)
  60. print "encode ok"
复制代码
整个工程是用cocosIDE生成的。这个工具会自动加密src下的lua,并在 AppDelegate.cpp中设置相应的密码与签名。xxTeaModule是对cocos2d-x\external\xxtea\xxtea.cpp的一个python封装。