Unity 文件加密


 /// 
    /// 对称加密算法类,AES、DES算法,据说AES更快一些,所以这里用AES
    /// 
    public class Symmetric
    {
        const string KEY = "WgsergmzsjdfgOEWRGNJRNGmkzaksme";
        const string IV = "SOJGGpjrepgjaskgpojAJGoe;lrmg";
        /// 
        /// 将字符串解码到固定长度的数组中
        /// 
        byte[] StringEncodeFixedLengthArray(string content,int length)
        {
            byte[] data=Encoding.ASCII.GetBytes(content);
            Array.Resize(ref data, length);
            return data;
        }
        /// 
        /// Aes加密
        /// 
        public byte[] AesEncrypt(byte[] data)
        {
            byte[] result;
            using (Aes aes = Aes.Create())
            {
                aes.Key = StringEncodeFixedLengthArray(KEY, 32);//32不要乱改,改成其他值可能会出错
                aes.IV = StringEncodeFixedLengthArray(IV, 16);//16不要乱改,改成其他值可能会出错

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
                result = encryptor.TransformFinalBlock(data, 0, data.Length);
                encryptor.Dispose();
            }

            return result;
        }
        /// 
        /// Aes解密
        /// 
        public byte[] AesDecrypt(byte[] data)
        {
            byte[] result;
            using (Aes aes = Aes.Create())
            {
                aes.Key = StringEncodeFixedLengthArray(KEY, 32);//32不要乱改,改成其他值可能会出错
                aes.IV = StringEncodeFixedLengthArray(IV, 16);//16不要乱改,改成其他值可能会出错

                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
                result = decryptor.TransformFinalBlock(data, 0, data.Length);
                decryptor.Dispose();
            }
            return result;
        }
        /// 
        /// Des加密
        /// 
        public byte[] DesEncrypt(byte[] data)
        {
            byte[] result;
            using (DES des = DES.Create())
            {
                des.Key = StringEncodeFixedLengthArray(KEY, 8);//8不要乱改,改成其他值可能会出错
                des.IV = StringEncodeFixedLengthArray(IV, 8);//8不要乱改,改成其他值可能会出错

                ICryptoTransform encryptor = des.CreateEncryptor(des.Key, des.IV);
                result = encryptor.TransformFinalBlock(data, 0, data.Length);
                encryptor.Dispose();
            }

            return result;
        }
        /// 
        /// Des解密
        /// 
        public byte[] DesDecrypt(byte[] data)
        {
            byte[] result;
            using (DES des = DES.Create())
            {
                des.Key = StringEncodeFixedLengthArray(KEY, 8);//8不要乱改,改成其他值可能会出错
                des.IV = StringEncodeFixedLengthArray(IV, 8);//8不要乱改,改成其他值可能会出错

                ICryptoTransform decryptor = des.CreateDecryptor(des.Key, des.IV);
                result = decryptor.TransformFinalBlock(data, 0, data.Length);
                decryptor.Dispose();
            }
            return result;
        }
    }

命名空间:

using System.Security.Cryptography;