Unity中数据和资源加密(异或加密,AES加密,MD5加密)

在项目开发中,始终会涉及到的一个问题,就是信息安全,在调用接口,或者加载的资源,都会涉及安全问题,因此就出现了各种各样的加密方式。

常见的也是目前用的最广的加密方式,分别是:DES、3DES、AES、MD5、XOR(异或)

其中DES、3DES、AES、MD5用在数据加密中偏多,特别是接口调用数据信息传输上。

XOR异或加密用在资源加密上偏多。

因此很多工程师会整理一个通用的加密工具类,因此我这边也同样整理了一个工具脚本。

但DES和3DES之前项目中没用到过,因此还没整理,等后续如果有碰到会再更新。

下面主要是AES、MD5、XOR加密方式

1、XOR(异或加密)

异或加密其实很简单,就是将二进制明文数据进行异或运算,解密时,只需要对密文再次异或运算即可。异或运算原理是,相同为 0,不同为 1

因此加密代码和解密代码一致,但是根据密钥可以是 单个byte,或者 多个byte,这就导致出现了,更复杂的加密方式,例如对明文数据索引的取余等等。当索引满足什么条件时进行加密,不满足时不进行加密。

例如下方代码

/// 
/// 异或操作
/// 
/// 
/// 
/// 
public static byte[] XorCipher(byte[] data, byte key = XorDefaultPassword)
{
    for (int i = 0; i < data.Length; i++)
    {
        data[i] ^= key;
    }
    return data;
}

/// 
/// 异或操作
/// 
///  数据 
///  密钥 
///  是否取余(数据索引,对key长度取余,不等于0时加密) 
/// 
public static byte[] XorCipher(byte[] data, byte[] key=null,bool isRemainder = true)
{
    if (key == null || key.Length <= 0) key = XorArrayPassword;

    for (int i = 0; i < data.Length; i++)
    {
        if (!isRemainder)
        {
            data[i] ^= key[i % key.Length];
        }
        else
        {
            if (i % key.Length != 0)
            {
                data[i] ^= key[i % key.Length];
            }
        }
    }
    return data;
}

2、MD5加密

MD5码是个很常见的东西,特别是在做资源热更新的,很多公司会对给资源文件一个MD5编码,用作版本管理,判断这个编码是否一致,一致就不更新,不一致就更新资源。但这个编码的计算方式也可以用来做数据的加密。

        ///  
        /// 加密数据 
        ///  
        ///  
        ///  
        ///  
        public static string EncryptByMD5(string content, string key = DefaultPassword)
        {
            var des = System.Security.Cryptography.DES.Create();
            byte[] inputByteArray;
            inputByteArray = System.Text.Encoding.Default.GetBytes(content);


            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(System.BitConverter.ToString(md5.ComputeHash(System.Text.Encoding.Default.GetBytes(key + "md5"))).Replace("-", null).Substring(0, 8));
            des.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(System.BitConverter.ToString(md5.ComputeHash(System.Text.Encoding.Default.GetBytes(key + "md5"))).Replace("-", null).Substring(0, 8));

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            System.Text.StringBuilder ret = new System.Text.StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

        ///  
        /// 解密数据 
        ///  
        ///  
        ///  
        ///  
        public static string DecryptByMD5(string content, string key = DefaultPassword)
        {
            var des = System.Security.Cryptography.DES.Create();
            int len;
            len = content.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = System.Convert.ToInt32(content.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(System.BitConverter.ToString(md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key + "md5"))).Replace("-", null).Substring(0, 8));
            des.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(System.BitConverter.ToString(md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key + "md5"))).Replace("-", null).Substring(0, 8));


            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }

3、AES加密

一度是目前实用最广泛的加密方式,虽然也被发现了破解方式,但安全性以及效率都还是比较高的加密方式,因此还在被广泛的使用中。

提供了几种方法:
1、字符串加密后返回字符串
2、字符串加密后返回字节数组
3、字节数组加密后返回字符串
4、字节数组加密后返回字节数组

   /// 
   /// AES加密
   /// 
   ///  原文 
   ///  密钥 
   ///  字节数组 
   public static byte[] EncryptToBytesByAes(string content, string key = DefaultPassword, string iv = DefaultPassword)
   {
       var keyData = System.Text.Encoding.Default.GetBytes(key);
       var ivData = System.Text.Encoding.Default.GetBytes(iv);

       byte[] encrypted;

       // Create an Aes object
       // with the specified key and IV.
       using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
       {
           aesAlg.Key = keyData;
           aesAlg.IV = ivData;
           aesAlg.Mode = System.Security.Cryptography.CipherMode.CBC;
           aesAlg.Padding = System.Security.Cryptography.PaddingMode.ISO10126;

           // Create an encryptor to perform the stream transform.
           System.Security.Cryptography.ICryptoTransform encryptor = aesAlg.CreateEncryptor();

           // Create the streams used for encryption.
           using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
           {
               using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
               {
                   using (System.IO.StreamWriter swEncrypt = new System.IO.StreamWriter(csEncrypt))
                   {
                       //Write all data to the stream.
                       swEncrypt.Write(content);
                   }
                   encrypted = msEncrypt.ToArray();
               }
           }
       }

       // Return the encrypted bytes from the memory stream.
       return encrypted;
   }

   /// 
   /// AES加密
   /// 
   ///  原文 
   ///  密钥 
   ///  字节数组 
   public static byte[] EncryptToBytesByAes(byte[] content, string key = DefaultPassword, string iv = DefaultPassword)
   {
       var keyData = System.Text.Encoding.Default.GetBytes(key);
       var ivData = System.Text.Encoding.Default.GetBytes(iv);

       byte[] encrypted;

       // Create an Aes object
       // with the specified key and IV.
       using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
       {
           aesAlg.Key = keyData;
           aesAlg.IV = ivData;
           aesAlg.Mode = System.Security.Cryptography.CipherMode.CBC;
           aesAlg.Padding = System.Security.Cryptography.PaddingMode.ISO10126;

           // Create an encryptor to perform the stream transform.
           System.Security.Cryptography.ICryptoTransform encryptor = aesAlg.CreateEncryptor();

           // Create the streams used for encryption.
           using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
           {
               using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
               {
                   using (System.IO.StreamWriter swEncrypt = new System.IO.StreamWriter(csEncrypt))
                   {
                       //Write all data to the stream.
                       swEncrypt.Write(content);
                   }
                   encrypted = msEncrypt.ToArray();
               }
           }
       }

       // Return the encrypted bytes from the memory stream.
       return encrypted;
   }

   /// 
   /// AES加密
   /// 
   ///  原文 
   ///  密钥 
   ///  字符串 
   public static string EncryptToStringByAes(string content, string key = DefaultPassword, string iv = DefaultPassword)
   {
       var keyData = System.Text.Encoding.Default.GetBytes(key);
       var ivData = System.Text.Encoding.Default.GetBytes(iv);

       byte[] encrypted;

       // Create an Aes object
       // with the specified key and IV.
       using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
       {
           aesAlg.Key = keyData;
           aesAlg.IV = ivData;
           aesAlg.Mode = System.Security.Cryptography.CipherMode.CBC;
           aesAlg.Padding = System.Security.Cryptography.PaddingMode.ISO10126;

           // Create an encryptor to perform the stream transform.
           System.Security.Cryptography.ICryptoTransform encryptor = aesAlg.CreateEncryptor();

           // Create the streams used for encryption.
           using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
           {
               using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
               {
                   using (System.IO.StreamWriter swEncrypt = new System.IO.StreamWriter(csEncrypt))
                   {
                       //Write all data to the stream.
                       swEncrypt.Write(content);
                   }
                   encrypted = msEncrypt.ToArray();
               }
           }
       }

       // Return the encrypted bytes from the memory stream.
       return System.Text.Encoding.Default.GetString(encrypted);
   }

   /// 
   /// AES加密
   /// 
   ///  原文 
   ///  密钥 
   ///  字符串 
   public static string EncryptToStringByAes(byte[] content, string key = DefaultPassword, string iv = DefaultPassword)
   {
       var keyData = System.Text.Encoding.Default.GetBytes(key);
       var ivData = System.Text.Encoding.Default.GetBytes(iv);

       byte[] encrypted;

       // Create an Aes object
       // with the specified key and IV.
       using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
       {
           aesAlg.Key = keyData;
           aesAlg.IV = ivData;
           aesAlg.Mode = System.Security.Cryptography.CipherMode.CBC;
           aesAlg.Padding = System.Security.Cryptography.PaddingMode.ISO10126;

           // Create an encryptor to perform the stream transform.
           System.Security.Cryptography.ICryptoTransform encryptor = aesAlg.CreateEncryptor();

           // Create the streams used for encryption.
           using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
           {
               using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
               {
                   using (System.IO.StreamWriter swEncrypt = new System.IO.StreamWriter(csEncrypt))
                   {
                       //Write all data to the stream.
                       swEncrypt.Write(content);
                   }
                   encrypted = msEncrypt.ToArray();
               }
           }
       }

       // Return the encrypted bytes from the memory stream.
       return System.Text.Encoding.Default.GetString(encrypted);
   }

   /// 
   /// AES解密
   /// 
   ///  加密数据 
   ///  密钥 
   ///  字节数组 
   public static byte[] DecryptToBytesByAes(byte[] data, string key = DefaultPassword, string iv = DefaultPassword)
   {
       var keyData = System.Text.Encoding.Default.GetBytes(key);
       var ivData = System.Text.Encoding.Default.GetBytes(iv);

       // the decrypted text.
       byte[] content;

       // Create an Aes object
       // with the specified key and IV.
       using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
       {
           aesAlg.Key = keyData;
           aesAlg.IV = ivData;
           aesAlg.Mode = System.Security.Cryptography.CipherMode.CBC;
           aesAlg.Padding = System.Security.Cryptography.PaddingMode.ISO10126;

           // Create a decryptor to perform the stream transform.
           System.Security.Cryptography.ICryptoTransform decryptor = aesAlg.CreateDecryptor();

           // Create the streams used for decryption.
           using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(data))
           {
               using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
               {
                   using (System.IO.StreamReader srDecrypt = new System.IO.StreamReader(csDecrypt))
                   {
                       // Read the decrypted bytes from the decrypting stream
                       // and place them in a string.
                       var Text = srDecrypt.ReadToEnd();

                       content = System.Text.Encoding.Default.GetBytes(Text);
                   }
               }
           }
       }

       return content;
   }

   /// 
   /// AES解密
   /// 
   ///  加密数据 
   ///  密钥 
   ///  字节数组 
   public static byte[] DecryptToBytesByAes(string data, string key = DefaultPassword, string iv = DefaultPassword)
   {
       var keyData = System.Text.Encoding.Default.GetBytes(key);
       var ivData = System.Text.Encoding.Default.GetBytes(iv);

       // the decrypted text.
       byte[] content;

       // Create an Aes object
       // with the specified key and IV.
       using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
       {
           aesAlg.Key = keyData;
           aesAlg.IV = ivData;
           aesAlg.Mode = System.Security.Cryptography.CipherMode.CBC;
           aesAlg.Padding = System.Security.Cryptography.PaddingMode.ISO10126;

           // Create a decryptor to perform the stream transform.
           System.Security.Cryptography.ICryptoTransform decryptor = aesAlg.CreateDecryptor();

           // Create the streams used for decryption.
           using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(System.Text.Encoding.Default.GetBytes(data)))
           {
               using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
               {
                   using (System.IO.StreamReader srDecrypt = new System.IO.StreamReader(csDecrypt))
                   {
                       // Read the decrypted bytes from the decrypting stream
                       // and place them in a string.
                       var Text = srDecrypt.ReadToEnd();

                       content = System.Text.Encoding.Default.GetBytes(Text);
                   }
               }
           }
       }

       return content;
   }

   /// 
   /// AES解密
   /// 
   ///  加密数据 
   ///  密钥 
   ///  字符串 
   public static string DecryptToStringByAes(byte[] data, string key = DefaultPassword, string iv = DefaultPassword)
   {
       var keyData = System.Text.Encoding.Default.GetBytes(key);
       var ivData = System.Text.Encoding.Default.GetBytes(iv);

       // the decrypted text.
       string content = string.Empty;

       // Create an Aes object
       // with the specified key and IV.
       using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
       {
           aesAlg.Key = keyData;
           aesAlg.IV = ivData;
           aesAlg.Mode = System.Security.Cryptography.CipherMode.CBC;
           aesAlg.Padding = System.Security.Cryptography.PaddingMode.ISO10126;

           // Create a decryptor to perform the stream transform.
           System.Security.Cryptography.ICryptoTransform decryptor = aesAlg.CreateDecryptor();

           // Create the streams used for decryption.
           using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(data))
           {
               using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
               {
                   using (System.IO.StreamReader srDecrypt = new System.IO.StreamReader(csDecrypt))
                   {
                       // Read the decrypted bytes from the decrypting stream
                       // and place them in a string.
                       content = srDecrypt.ReadToEnd();
                   }
               }
           }
       }

       return content;
   }

   /// 
   /// AES解密
   /// 
   ///  加密数据 
   ///  密钥 
   ///  字节数组 
   public static string DecryptToStringByAes(string data, string key = DefaultPassword, string iv = DefaultPassword)
   {
       var keyData = System.Text.Encoding.Default.GetBytes(key);
       var ivData = System.Text.Encoding.Default.GetBytes(iv);

       // the decrypted text.
       string content = string.Empty;

       // Create an Aes object
       // with the specified key and IV.
       using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
       {
           aesAlg.Key = keyData;
           aesAlg.IV = ivData;
           aesAlg.Mode = System.Security.Cryptography.CipherMode.CBC;
           aesAlg.Padding = System.Security.Cryptography.PaddingMode.ISO10126;

           // Create a decryptor to perform the stream transform.
           System.Security.Cryptography.ICryptoTransform decryptor = aesAlg.CreateDecryptor();

           // Create the streams used for decryption.
           using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(System.Text.Encoding.Default.GetBytes(data)))
           {
               using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
               {
                   using (System.IO.StreamReader srDecrypt = new System.IO.StreamReader(csDecrypt))
                   {
                       // Read the decrypted bytes from the decrypting stream
                       // and place them in a string.
                       content = srDecrypt.ReadToEnd();
                   }
               }
           }
       }

       return content;
   }

目前整理的就这几种,之后如果有更新,再更新添加过来。

你可能感兴趣的:(unity,前端)