UntiyAssetBundle加密可行性分析

背景

我们发现市面上有其他游戏使用公司的游戏资源,现有的游戏资源并未加密处理。为了提高破解的门槛,想对资源进行加密处理。

异或加密方式可行性分析

  1. 为什么使用异或加密
    采取异或加密的原因在于加解密方式简单,解密性能开销较低,另外也不会改变文件大小。
  2. 异或加密带来的AssetBundle加载api调用修改
    使用加密的AssetBundle需要先把文件读取到byte数组,再对byte数组进行异或解密处理,最后再调用
    原来项目使用AssetBundle.LoadFromMemory/AssetBundle.LoadFromMemoryAsync api进行加载。
  3. 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:

  1. The AssetBundle data must start at stream position zero.
  2. Unity sets the seek position to zero before it loads the AssetBundle data.
  3. 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.
  4. stream.CanRead must return true.
  5. stream.CanSeek must return true.
  6. It must be accessible from threads different to the main thread. Seek() and Read() can be called from any Unity native thread.
  7. 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).
  8. 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进行加密处理。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • 原文地址:http://gad.qq.com/article/detail/7180936作者:Loki+XUni...
    重装机霸阅读 8,074评论 0 41
  • 这部分主要讨论了AssetBundle的如下知识: AssetBundle的基础知识 使用AssetBundle的...
    Wenchao阅读 1,524评论 0 5
  • 这一章来说说AssetBundles,介绍下它的基础系统,还有一些和AssetBundles进行交互的核心API。...
    莫铭阅读 2,743评论 6 10
  • 首先附上原文链接:https://unity3d.com/cn/learn/tutorials/topics/be...
    Bonging阅读 729评论 0 0
  • 翻译:莫铭原文地址:AssetBundle usage patterns 本系列中的上一篇文章覆盖了AssetBu...
    莫铭阅读 5,126评论 1 12