Unity 文件加密
/// <summary> /// 对称加密算法类,AES、DES算法,据说AES更快一些,所以这里用AES /// </summary> public class Symmetric { const string KEY = "WgsergmzsjdfgOEWRGNJRNGmkzaksme"; const string IV = "SOJGGpjrepgjaskgpojAJGoe;lrmg"; /// <summary> /// 将字符串解码到固定长度的数组中 /// </summary> byte[] StringEncodeFixedLengthArray(string content,int length) { byte[] data=Encoding.ASCII.GetBytes(content); Array.Resize(ref data, length); return data; } /// <summary> /// Aes加密 /// </summary> 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; } /// <summary> /// Aes解密 /// </summary> 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; } /// <summary> /// Des加密 /// </summary> 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; } /// <summary> /// Des解密 /// </summary> 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;
博客园Jason_c微信打赏码
如果本篇文档对你有帮助,打赏Jason_c根华子吧,他的私房钱被老婆没收了,呜呜!