背景
我们发现市面上有其他游戏使用公司的游戏资源,现有的游戏资源并未加密处理。为了提高破解的门槛,想对资源进行加密处理。
异或加密方式可行性分析
- 为什么使用异或加密
采取异或加密的原因在于加解密方式简单,解密性能开销较低,另外也不会改变文件大小。 - 异或加密带来的AssetBundle加载api调用修改
使用加密的AssetBundle需要先把文件读取到byte数组,再对byte数组进行异或解密处理,最后再调用
原来项目使用AssetBundle.LoadFromMemory/AssetBundle.LoadFromMemoryAsync api进行加载。 - LoadFromFile/LoadFromFileAsync与LoadFromMemory/LoadFromMemoryAsync进行对比
3.1 官方信息
AssetBundle.LoadFromFile(Async)
AssetBundle.LoadFromFile is a highly-efficient API intended for loading uncompressed or LZ4-compressed AssetBundle from local storage, such as a hard disk or an SD card.
On desktop standalone, console, and mobile platforms, the API will only load the AssetBundle's header, and will leave the remaining data on disk. The AssetBundle's Objects will be loaded on-demand as loading methods (e.g. AssetBundle.Load) are called or as their InstanceIDs are dereferenced. No excess memory will be consumed in this scenario. In the Unity Editor, the API will load the entire AssetBundle into memory, as if the bytes were read off disk and AssetBundle.LoadFromMemoryAsync was used. This API can cause memory spikes to appear during AssetBundle loading if the project is profiled in the Unity Editor. This should not affect performance on-device and these spikes should be re-tested on-device before taking remedial action.
Note: On Android devices with Unity 5.3 or older, this API will fail when trying to load AssetBundles from the Streaming Assets path. This issue has been resolved in Unity 5.4. For more details, see the section Distribution - shipped with project section of the AssetBundle usage patterns chapter.
AssetBundle.LoadFromMemory(Async)
Unity's recommendation is not to use this API.
AssetBundle.LoadFromMemoryAsync loads an AssetBundle from a managed-code byte array (byte[] in C#). It will always copy the source data from the managed-code byte array into a newly-allocated, contiguous block of native memory. If the AssetBundle is LZMA compressed, it will decompress the AssetBundle while copying. Uncompressed and LZ4-compressed AssetBundles will be copied verbatim.
The peak amount of memory consumed by this API will be at least twice the size of the AssetBundle: one copy in native memory created by the API, and one copy in the managed byte array passed to the API. Assets loaded from an AssetBundle created via this API will therefore be duplicated three times in memory: once in the managed-code byte array, once in the native-memory copy of the AssetBundle and a third time in GPU or system memory for the asset itself.
Prior to Unity 5.3.3, this API was known as ****AssetBundle.CreateFromMemory****. Its functionality has not changed.
通过上述的信息,以我们未加密的AssetBundle为例,我们知道AssetBundle.LoadFromFile(Async)和AssetBundle.LoadFromMemory(Async)得到AssetBundle付出的代价是不一样的,前者只加载了AssetBundle的头文件信息,后者需要先申请1份文件大小的空间给byte数组使用,调用AssetBundle.LoadFromMemory(Async)又将这份byte数组再拷贝一份,总共占用了2x文件大小的byte数组。cpu方面,因为需要开辟空间拷贝数组,也可以知道AssetBundle.LoadFromMemory(Async)执行也比AssetBundle.LoadFromFile(Async)要慢。
3.2 测试
前面说道AssetBundle.LoadFromMemory(Async)执行也比AssetBundle.LoadFromFile(Async)要慢,但是慢多少也没有一个明确的结果,所以做了一个小实验
3.2.1 cpu测试:cache大小为1mb
- 读取超过cache大小的文件:
读取设备本地的assetbundle文件并加载asset,读取100次,计算读取asset的平均值
同步加密加载一个29mb的文件比之前加载方式多耗时 92ms 比原来加载时间183ms多50%
异步加密加载一个29mb的文件比之前加载方式多耗时 73ms 比原来加载时间204.5ms多36% - 读取100个不超过cache的文件
读取在cache内100个文件:分别测试3次,计算读取asset的平均值
同步加密加载:27ms 原来加载:28ms 基本无区别
异步加密加载:39ms 原来加载:38.3ms 基本无区别
3.3 存在的问题和解决思路(个人不成熟的想法)
- 读取文件内存问题:读取文件使用一个cache的byte数组,在cache size范围内的文件使用cache数组读取,而超过范围新建一个对应大小bytes进行处理,使用完再释放临时创建的数组,即使如此处理也不能避免出现2xassetbundle文件大小的内存峰值占用。
- 对于AssetBundle.LoadFromMemory(Async)相比AssetBundle.LoadFromFile(Async)占用一份文件大小的内存问题:想在Asset.LoadAsset之后,不再将AssetBundle加入缓存池,调用AssetBundle.Unload(false)将Assetbundle释放掉,可以减少Assetbundle的调用,但是这样会有一个严重的问题:AssetBundle.LoadAsset加载出来的objects需要我们自己妥善destory掉,不然会出现重复的问题。
- AndroidStreamingAssets加载问题:在手机上我们Assetbundle有两个存放路径,一个是在包内的Streaming Assets,另一个是在包外Assetbundle的下载路径。而在Android平台Streaming Assets是存储在apk里面,不能使用filestream直接读取,只能使用Untiy封装的接口如UnityEngine.WWW去读取,最终得到WWW.bytes。所以无论文件大小是否超过cache size都不能使用cache的byte数组直接存储assetbundle的数据。
4.使用流方式读取
Unity2017新增了AssetBundle.LoadFromStream(Async),从流中读取AssetBundle,它的优点是跟AssetBundle.LoadFromFile(Async)一样读取AssetBundle的头文件,不会像AssetBundle.LoadFromMemory(Async)增加很多内存占用。不过这个api有如下几个限制
The following are restrictions on a Stream object to optimize AssetBundle data loading:
- The AssetBundle data must start at stream position zero.
- Unity sets the seek position to zero before it loads the AssetBundle data.
- Unity assumes the read position in the stream is not altered by any other process. This allows the Unity process to read from the stream without having to call Seek() before every read.
- stream.CanRead must return true.
- stream.CanSeek must return true.
- It must be accessible from threads different to the main thread. Seek() and Read() can be called from any Unity native thread.
- In certain circumstances Unity will try to read passed the size of the AssetBundle data. The Stream implementation must gracefully handle this without throwing exceptions. The Stream implementation must also return the actual number of bytes read (not including any bytes passed the end of the AssetBundle data).
- When starting at the end of the AssetBundle data and trying to read data the Stream implementation must return 0 bytes read and not throw exceptions.
如果使用该接口,需要自定义一个继承FileStream类,在构造方法传入异或的key,然后在Read和Write方法内对byte数组进行异或加密解密处理。
public class AssetBundleEncryptStream : FileStream
{
private byte key;
public AssetBundleEncryptStream(byte key,string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) : base(path, mode, access, share, bufferSize, useAsync)
{
this.key = key;
}
public AssetBundleEncryptStream(byte key, string path, FileMode mode) : base(path, mode)
{
this.key = key;
}
public override int Read(byte[] array, int offset, int count)
{
var index = base.Read(array, offset, count);
for (int i = 0; i < array.Length; i++)
{
array[i] ^= key;
}
return index;
}
public override void Write(byte[] array, int offset, int count)
{
for (int i = 0; i < array.Length; i++)
{
array[i] ^= key;
}
base.Write(array, offset, count);
}
}
- 上述的第一条就限制了我们通过在文件头增加多余数据来加密的可能。
- 另外这个接口也支持Android StreamingAssets目录下AssetBundle的读取,因为无法创建对应的流。假如使用AssetBundle.LoadFromStream(Async),在Android需要将StreamingAssets的文件拷贝到包外,然后进行读取。但是这样不仅增加了拷贝的步骤(影响资源加载速度),而且假如用户的磁盘空间不足的时候,拷贝容易失败,但是资源无法读取。
结语
从上面得知使用AssetBundle.LoadFromMemory(Async)进行AssetBundle加载不仅速度较慢,而且会带来很大的内存占用,从而影响游戏性能。而AssetBundle.LoadFromStream(Async)在Android平台的应用受到了限制。所以综上所述,由于加密解密AssetBundle的代价过大,暂不对AssetBundle进行加密处理。