Unity3D 使用AES方式加密与解密文件

今天小编为大家介绍如何把保存的文件采用AES 方式加密/解密
   1.新建一个 unity3d 项目,新建一个Test.unity场景,场景里面需要有一个摄像机,并且在摄像机上附加一个SaveAESFile.cs组件类,另外还需要在项目新建一个Resources文件夹,这个文件夹为了存放加密的文件。

       Unity3D 使用AES方式加密与解密文件_第1张图片 


   2.首先需要一个辅助类AES.cs和一个实体类People.cs,然后代码如下:

      ①AES.cs代码如下:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
 
namespace Utils
{
    /// 
    /// AES加密解密
    /// 
    public class AES
    {
        #region 加密
        #region 加密字符串
        /// 
        /// AES 加密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
        /// 
        /// 待加密密文
        /// 加密密钥
        public static string AESEncrypt(string EncryptString, string EncryptKey)
        {
            return Convert.ToBase64String(AESEncrypt(Encoding.Default.GetBytes(EncryptString), EncryptKey));
        }
        #endregion
 
        #region 加密字节数组
        /// 
        /// AES 加密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
        /// 
        /// 待加密密文
        /// 加密密钥
        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;
        }
        #endregion
        #endregion
 
        #region 解密
        #region 解密字符串
        /// 
        /// AES 解密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
        /// 
        /// 待解密密文
        /// 解密密钥
        public static string AESDecrypt(string DecryptString, string DecryptKey)
        {
            return Convert.ToBase64String(AESDecrypt(Encoding.Default.GetBytes(DecryptString), DecryptKey));
        }
        #endregion
 
        #region 解密字节数组
        /// 
        /// AES 解密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
        /// 
        /// 待解密密文
        /// 解密密钥
        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;
        }
        #endregion
        #endregion
 
    }
}


②People.cs 代码如下:
using System;
namespace Assets
{
    [Serializable]
 
    public class People
    {
        public People()
        {
        }
        public int ID;
        public string Name;
        public int Age;
    }
}

 3.直接是SaveAESFile.cs的核心代码

using UnityEngine;
using Assets;
using System.Text;
using System;
using System.IO;
using Utils;
 
public class SaveAESFile : MonoBehaviour
{
 
    public string FilePath = "";
    private People _people;
    private string info = "";
 
    /// 
    /// AES 密码保存
    /// 
    private const string _password = "qq123";
 
    /// 
    /// 一次处理的明文字节数
    /// 
    public static readonly int encryptSize = 10000000;
    /// 
    /// 一次处理的密文字节数
    /// 
    public static readonly int decryptSize = 10000016;
 
 
    void Awake()
    {
        FilePath = Application.dataPath + @"/Resources/SaveAESFile.json";
    }
 
    void OnGUI()
    {
        // 文本显示
        GUI.Label(new Rect(50, 200, 200, 50), info);
 
 
        // 第一个文字按钮
        GUI.color = Color.yellow;  //按钮文字颜色  
        GUI.backgroundColor = Color.red; //按钮背景颜色
 
        if (GUI.Button(new Rect(50, 250, 200, 30), "保存加密文件"))
        {
            info = "保存加密文件!";
            AESSaveFile();
        }
 
        // 第二个图片按钮
        GUI.color = Color.white;  //按钮文字颜色  
        GUI.backgroundColor = Color.red; //按钮背景颜色
 
        if (GUI.Button(new Rect(50, 300, 200, 30), "显示解密文件"))
        {
            ShowAESFile();
            info = "显示解密文件!";
            People temp = _people;
            info = "ID:" + _people.ID + "   " + "Name:" + _people.Name + "    " + "Age:" + _people.Age;
        }
 
    }
 
 
    void AESSaveFile()
    {
        AddData();
        byte[] texts = new byte[] { };
        try
        {
            string autoSaveJson = JsonUtility.ToJson(_people);
            //加密
            texts = Utils.AES.AESEncrypt(Encoding.UTF8.GetBytes(autoSaveJson), _password);
        }
        catch (Exception e)
        {
            Debug.LogError("Message:" + e.Message);
        }
        if (File.Exists(FilePath))
        {
            File.Delete(FilePath);
        }
        using (FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Write))
        {
            if (fs != null)
            {
                fs.Write(texts, 0, texts.Length);
                fs.Flush();
                fs.Dispose();
            }
        }
    }
 
    void ShowAESFile()
    {
        try
        {
            string DecrypText = string.Empty;
            using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
            {
                if (fs.Length > 0)
                {
                    int blockCount = ((int)fs.Length - 1) / decryptSize + 1;
                    for (int i = 0; i < blockCount; i++)
                    {
                        int size = decryptSize;
                        if (i == blockCount - 1) size = (int)(fs.Length - i * decryptSize);
                        byte[] bArr = new byte[size];
                        fs.Read(bArr, 0, size);
                        //解密
                        byte[] result = AES.AESDecrypt(bArr, _password);
                        DecrypText += Encoding.UTF8.GetString(result);
                    }
                    fs.Close();
                    fs.Dispose();
                }
            }
            _people = JsonUtility.FromJson(DecrypText);
        }
        catch (Exception e)
        {
            Debug.LogError("Message:" + e.Message);
        }
    }
 
    void AddData()
    {
        _people = new People();
        _people.ID = 1;
        _people.Name = "小白兔";
        _people.Age = 18;
    }
}

  4.最后便是执行项目看效果啦!
    ①点击解密保存文件,我们会发现在Resources下面会生成一个.json文件,如图下:
    
       Unity3D 使用AES方式加密与解密文件_第2张图片 


       Unity3D 使用AES方式加密与解密文件_第3张图片 
         
    ②当我们点击按钮解密显示文件时,会发现加密的文件的内容被解密,如图下:
   
       Unity3D 使用AES方式加密与解密文件_第4张图片 

Unity3D 使用AES方式加密与解密文件_第5张图片

你可能感兴趣的:(Unity)