找回密码
 立即注册
查看: 268|回复: 0

Unity AssetBundle文件资源加密、解密整理合集

[复制链接]
发表于 2022-4-24 10:18 | 显示全部楼层 |阅读模式
一、unity中国区官方加密

      加密:AssetBundle.SetAssetBundleEncryptKey();
      解密:AssetBundle.SetAssetBundleDecryptKey();
二、二进制加密

/// <summary>
/// 加密
/// </summary>
private void EncryptFile()
{
    string resFile = "C:/Workspace/UnityProjects/Demo/Assets/StreamingAssets/prefabs.dat";//需要加密文件的路径
    var data_bytes = File.ReadAllBytes(resFile);
    var key_bytes = System.Text.Encoding.UTF8.GetBytes("123");//密钥"123"
    for (int i = 0; i < data_bytes.Length; i++){
         data_bytes = (byte) (data_bytes ^ key_bytes[i % key_bytes.Length]);
    }
    File.WriteAllBytes(resFile,data_bytes);
    Debug.Log("加密成功!!!!");
}

// 解密:
AssetBundle.LoadFromMemoryAsync();//异步
AssetBundle.LoadFromMemory();//同步详细可以去:【Unity】AssetBundle简单的加密解密_空空如我-程序员资料_assetbundle加密解密 - 程序员资料
三、在AssetBundle头部加入部分字节

/// <summary>
/// 加密
/// </summary>   
public static void EncryptFile()
{
       string fileFile = "C:/Workspace/UnityProjects/Demo/Assets/StreamingAssets/prefabs.dat";
       uint offset = 96;
       byte[] filedata = File.ReadAllBytes(fileFile);
       int filelen = ((int)offset + filedata.Length);
       byte[] buffer = new byte[filelen];
               
       for (int slen = 0; slen < offset; slen++)
       {
           buffer[slen] = 1;
       }
       for (int slen = 0; slen < filedata.Length; slen++)
       {
           buffer[slen + offset] = filedata[slen];
       }
       FileStream fs = File.OpenWrite(fileFile);
       fs.Write(buffer, 0, filelen);
       fs.Close();
}

/// <summary>
/// 同步解密
/// </summary>
protected void DecryptionFile(string assetBundlePatchFile)
{
    uint offSet = 96;
    AssetBundle abBundle = AssetBundle.LoadFromFile(assetBundlePatchFile, 0,offSet);
}

/// <summary>
/// 异步解密
/// </summary>   
protected IEnumerator DecryptionFile(string assetBundlePatchFile)
{
    uint offSet = 96;
    AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(assetBundlePatchFile, 0,offSet);
    yield return request;
    AssetBundle abBundle = request.assetBundle;
}详细可以去:Unity 打包 AssetBundle加密
四、DES加密算法

#region  定义秘钥

//加解密密钥,可自行替换
protected static string tmpDESkey = "gBPZodCkn6T";
// Create sha256 hash
static SHA256 mySHA256 = SHA256Managed.Create();
protected  static byte[] basekey = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(tmpDESkey));
// Create secret IV
protected static byte[] baseiv = new byte[16] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };

#endregion

#region  加密   
public static string EncryptFile(string plainText)
{
    byte[] key = basekey;
    byte[] iv = baseiv;
           
    Aes encryptor = Aes.Create();

    encryptor.Mode = CipherMode.CBC;

    // Set key and IV
    byte[] aesKey = new byte[32];
    Array.Copy(key, 0, aesKey, 0, 32);
    encryptor.Key = aesKey;
    encryptor.IV = iv;

    // Instantiate a new MemoryStream object to contain the encrypted bytes
    MemoryStream memoryStream = new MemoryStream();

    // Instantiate a new encryptor from our Aes object
    ICryptoTransform aesEncryptor = encryptor.CreateEncryptor();

    // Instantiate a new CryptoStream object to process the data and write it to the
    // memory stream
    CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);

    // Convert the plainText string into a byte array
    byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);

    // Encrypt the input plaintext string
    cryptoStream.Write(plainBytes, 0, plainBytes.Length);

    // Complete the encryption process
    cryptoStream.FlushFinalBlock();

    // Convert the encrypted data from a MemoryStream to a byte array
    byte[] cipherBytes = memoryStream.ToArray();

    // Close both the MemoryStream and the CryptoStream
    memoryStream.Close();
    cryptoStream.Close();

    // Convert the encrypted byte array to a base64 encoded string
    string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);

    // Return the encrypted data as a string
    return cipherText;
}
#endregion

#region 解密
public static string DecryptionFile(string cipherText)
{
   byte[] key = basekey;
   byte[] iv = baseiv;

   // Instantiate a new Aes object to perform string symmetric encryption
   Aes encryptor = Aes.Create();

   encryptor.Mode = CipherMode.CBC;

   // Set key and IV
   byte[] aesKey = new byte[32];
   Array.Copy(key, 0, aesKey, 0, 32);
   encryptor.Key = aesKey;
   encryptor.IV = iv;

   // Instantiate a new MemoryStream object to contain the encrypted bytes
   MemoryStream memoryStream = new MemoryStream();

   // Instantiate a new encryptor from our Aes object
   ICryptoTransform aesDecryptor = encryptor.CreateDecryptor();

   // Instantiate a new CryptoStream object to process the data and write it to the
   // memory stream
   CryptoStream cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Write);

   // Will contain decrypted plaintext
   string plainText = String.Empty;
   try
   {
       // Convert the ciphertext string into a byte array
       byte[] cipherBytes = Convert.FromBase64String(cipherText);

       // Decrypt the input ciphertext string
       cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);

       // Complete the decryption process
       cryptoStream.FlushFinalBlock();
       // Convert the decrypted data from a MemoryStream to a byte array
       byte[] plainBytes = memoryStream.ToArray();

       // Convert the decrypted byte array to string
       plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
   }
   finally
   {
      // Close both the MemoryStream and the CryptoStream
       memoryStream.Close();
       cryptoStream.Close();
   }

   // Return the decrypted data as a string
  return plainText;
  }
#endregion代码转载:https://www.jianshu.com/p/ad317d9f93d8
DES加密算法详解:经典的DES算法详解_yasinzhang的博客-CSDN博客_des算法
五、AES加密算法

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
public class AES
{
    // 加密识别头(用来识别文件是否已经加密过)
    private const string AES_HEAD = "AESEncrypt";

    /// <summary>
    /// 文件加密,传入文件路径
    /// </summary>
    /// <param name="path"></param>
    /// <param name="EncrptyKey"></param>
    public static void AESFileEncrypt(string path, string EncrptyKey)
    {
        if (!File.Exists(path))
            return;
        try
        {
            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                if (fs != null)
                {
                    //读取字节头,判断是否已经加密过了
                    byte[] headBuff = new byte[10];
                    fs.Read(headBuff, 0, headBuff.Length);
                    string headTag = Encoding.UTF8.GetString(headBuff);
                    if (headTag == AES_HEAD)
                    {
#if UNITY_EDITOR
                        Debug.Log(path + "已经加密过了!");
#endif
                        return;
                    }
                    //加密并且写入字节头
                    fs.Seek(0, SeekOrigin.Begin);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, Convert.ToInt32(fs.Length));
                    fs.Seek(0, SeekOrigin.Begin);
                    fs.SetLength(0);
                    byte[] headBuffer = Encoding.UTF8.GetBytes(AES_HEAD);
                    fs.Write(headBuffer, 0, headBuffer.Length);
                    byte[] EncBuffer = AESEncrypt(buffer, EncrptyKey);
                    fs.Write(EncBuffer, 0, EncBuffer.Length);
                }
            }
        }
        catch (Exception e)
        {
            Debug.LogError(e);
        }
    }

    /// <summary>
    /// 文件解密,传入文件路径(会改动加密文件,不适合运行时)
    /// </summary>
    /// <param name="path"></param>
    /// <param name="EncrptyKey"></param>
    public static void AESFileDecrypt(string path, string EncrptyKey)
    {
        if (!File.Exists(path))
        {
            return;
        }
        try
        {
            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                if (fs != null)
                {
                    byte[] headBuff = new byte[10];
                    fs.Read(headBuff, 0, headBuff.Length);
                    string headTag = Encoding.UTF8.GetString(headBuff);
                    if (headTag == AES_HEAD)
                    {
                        byte[] buffer = new byte[fs.Length - headBuff.Length];
                        fs.Read(buffer, 0, Convert.ToInt32(fs.Length - headBuff.Length));
                        fs.Seek(0, SeekOrigin.Begin);
                        fs.SetLength(0);
                        byte[] DecBuffer = AESDecrypt(buffer, EncrptyKey);
                        fs.Write(DecBuffer, 0, DecBuffer.Length);
                    }
                }
            }
        }
        catch (Exception e)
        {
            Debug.LogError(e);
        }
    }

    /// <summary>
    /// 文件解密,传入文件路径,返回字节
    /// </summary>
    /// <returns></returns>
    public static byte[] AESFileByteDecrypt(string path, string EncrptyKey)
    {
        if (!File.Exists(path))
        {
            return null;
        }
        byte[] DecBuffer = null;
        try
        {
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                if (fs != null)
                {
                    byte[] headBuff = new byte[10];
                    fs.Read(headBuff, 0, headBuff.Length);
                    string headTag = Encoding.UTF8.GetString(headBuff);
                    if (headTag == AES_HEAD)
                    {
                        byte[] buffer = new byte[fs.Length - headBuff.Length];
                        fs.Read(buffer, 0, Convert.ToInt32(fs.Length - headBuff.Length));
                        DecBuffer = AESDecrypt(buffer, EncrptyKey);
                    }
                }
            }
        }
        catch (Exception e)
        {
            Debug.LogError(e);
        }

        return DecBuffer;
    }

    /// <summary>
    /// AES 加密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
    /// </summary>
    /// <param name="EncryptString">待加密密文</param>
    /// <param name="EncryptKey">加密密钥</param>
    public static string AESEncrypt(string EncryptString, string EncryptKey)
    {
        return Convert.ToBase64String(AESEncrypt(Encoding.Default.GetBytes(EncryptString), EncryptKey));
    }

    /// <summary>
    /// AES 加密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
    /// </summary>
    /// <param name="EncryptString">待加密密文</param>
    /// <param name="EncryptKey">加密密钥</param>
    public static byte[] AESEncrypt(byte[] EncryptByte, string EncryptKey)
    {
        if (EncryptByte.Length == 0) { throw (new Exception("明文不得为空")); }
        if (string.IsNullOrEmpty(EncryptKey)) { throw (new Exception("密钥不得为空")); }
        byte[] m_strEncrypt;
        byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ==");
        byte[] m_salt = Convert.FromBase64String("gsf4jvkyhye5/d7k8OrLgM==");
        Rijndael m_AESProvider = Rijndael.Create();
        try
        {
            MemoryStream m_stream = new MemoryStream();
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(EncryptKey, m_salt);
            ICryptoTransform transform = m_AESProvider.CreateEncryptor(pdb.GetBytes(32), m_btIV);
            CryptoStream m_csstream = new CryptoStream(m_stream, transform, CryptoStreamMode.Write);
            m_csstream.Write(EncryptByte, 0, EncryptByte.Length);
            m_csstream.FlushFinalBlock();
            m_strEncrypt = m_stream.ToArray();
            m_stream.Close(); m_stream.Dispose();
            m_csstream.Close(); m_csstream.Dispose();
        }
        catch (IOException ex) { throw ex; }
        catch (CryptographicException ex) { throw ex; }
        catch (ArgumentException ex) { throw ex; }
        catch (Exception ex) { throw ex; }
        finally { m_AESProvider.Clear(); }
        return m_strEncrypt;
    }


    /// <summary>
    /// AES 解密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
    /// </summary>
    /// <param name="DecryptString">待解密密文</param>
    /// <param name="DecryptKey">解密密钥</param>
    public static string AESDecrypt(string DecryptString, string DecryptKey)
    {
        return Convert.ToBase64String(AESDecrypt(Encoding.Default.GetBytes(DecryptString), DecryptKey));
    }

    /// <summary>
    /// AES 解密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
    /// </summary>
    /// <param name="DecryptString">待解密密文</param>
    /// <param name="DecryptKey">解密密钥</param>
    public static byte[] AESDecrypt(byte[] DecryptByte, string DecryptKey)
    {
        if (DecryptByte.Length == 0) { throw (new Exception("密文不得为空")); }
        if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); }
        byte[] m_strDecrypt;
        byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ==");
        byte[] m_salt = Convert.FromBase64String("gsf4jvkyhye5/d7k8OrLgM==");
        Rijndael m_AESProvider = Rijndael.Create();
        try
        {
            MemoryStream m_stream = new MemoryStream();
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(DecryptKey, m_salt);
            ICryptoTransform transform = m_AESProvider.CreateDecryptor(pdb.GetBytes(32), m_btIV);
            CryptoStream m_csstream = new CryptoStream(m_stream, transform, CryptoStreamMode.Write);
            m_csstream.Write(DecryptByte, 0, DecryptByte.Length);
            m_csstream.FlushFinalBlock();
            m_strDecrypt = m_stream.ToArray();
            m_stream.Close(); m_stream.Dispose();
            m_csstream.Close(); m_csstream.Dispose();
        }
        catch (IOException ex) { throw ex; }
        catch (CryptographicException ex) { throw ex; }
        catch (ArgumentException ex) { throw ex; }
        catch (Exception ex) { throw ex; }
        finally { m_AESProvider.Clear(); }
        return m_strDecrypt;
    }
}

代码转载:Unity中使用AES加密方式进行AssetBundle加密 - Blink小站-极客瞬间
AES加密算法详解:AES加密算法的详细介绍与实现_TimeShatter的博客-CSDN博客_aes加密
六、提取unity资源工具AssetStudio

下载地址(GitHub):https://github.com/Perfare/AssetStudio
根据需求选择对应ZIP:


下载完毕解压打开AssetStudioGUI.exe:



七、所有加密优缺点对比

加密方式缺点
unity官方不同电脑会出现MD5不稳定
二进制内存中会存在双份内存
头部加入部分字节简单易破解,直接删除前缀就可以破解
加密算法缺点
DES加密算法分组和密钥短、生命周期短、运算速度慢
AES加密算法分组和密钥长度灵活、内存低、运算快
备注:官方的使用最方便简单安全性也不错,就是打包MD5值不稳定热更会不方便,有需要可以换MD5思路也是很不错的方法。二进制加载的时候会用到LoadFromMemory ,这个很占内存一般手游不适合,内存足够资源小不在乎也可以。以上都不行可以考虑:LoadFromStream 详细:Unity3D研究院之加密Assetbundle不占内存(一百零五) | 雨松MOMO程序研究院

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-9-22 13:36 , Processed in 0.067802 second(s), 23 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表