正在阅读:对称加密之AES及压缩加密解密解压综合实战对称加密之AES及压缩加密解密解压综合实战

2017-03-11 22:17 出处:其他 作者:佚名 责任编辑:lixianmei

 对称加密:就是采用这种加密方法的双方使用方式用同样的密钥进行加密和解密。密钥是控制加密及解密过程的指令。算法是一组规则,规定如何进行加密和解密。

因此加密的安全性不仅取决于加密算法本身,密钥管理的安全性更是重要。因为加密和解密都使用同一个密钥,如何把密钥安全地传递到解密者手上就成了必须要解决的问题。

由此可见密钥传递也是比较重要的一环,一般都是通过对密钥二次加密的方式,进行密钥的传输

加密实现代码:

 
  1. public static byte[] encryptStringToBytes_AES(byte[] fileContentBytes, byte[] Key, byte[] IV)  
  2. {  
  3.     // Check arguments.  
  4.     if (fileContentBytes == null || fileContentBytes.Length <= 0)  
  5.         throw new ArgumentNullException("plainText");  
  6.     if (Key == null || Key.Length <= 0)  
  7.         throw new ArgumentNullException("Key");  
  8.     if (IV == null || IV.Length <= 0)  
  9.         throw new ArgumentNullException("IV");  
  10.     MemoryStream msEncrypt = null;  
  11.     AesCryptoServiceProvider aesAlg = null;  
  12.     try  
  13.     {  
  14.         aesAlg = new AesCryptoServiceProvider();  
  15.    
  16.         aesAlg.Padding = PaddingMode.PKCS7;  
  17.         aesAlg.Key = Key;  
  18.         aesAlg.IV = IV;  
  19.    
  20.         ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);  
  21.    
  22.         msEncrypt = new MemoryStream();  
  23.         using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))  
  24.         {  
  25.             csEncrypt.Write(fileContentBytes, 0, fileContentBytes.Length);  
  26.             csEncrypt.FlushFinalBlock();  
  27.         }  
  28.     }  
  29.     catch (Exception ex)  
  30.     {  
  31.    
  32.     }  
  33.     finally  
  34.     {  
  35.         if (aesAlg != null)  
  36.             aesAlg.Clear();  
  37.     }  
  38.     return msEncrypt.ToArray();  

解密代码实现:

 
  1. public static byte[] decryptBytes(byte[] cipherText, byte[] Key, byte[] IV)  
  2. {  
  3.     if (cipherText == null || cipherText.Length <= 0)  
  4. __箰讆__360__璺拶__       throw new ArgumentNullException("cipherText");  
  5.     if (Key == null || Key.Length <= 0)  
  6.         throw new ArgumentNullException("Key");  
  7.     if (IV == null || IV.Length <= 0)  
  8.         throw new ArgumentNullException("IV");  
  9.     AesCryptoServiceProvider aesAlg = null;  
  10.     byte[] buffer = null;  
  11.     try  
  12.     {  
  13.         using (aesAlg = new AesCryptoServiceProvider())  
  14.         {  
  15.             aesAlg.Padding = PaddingMode.PKCS7;  
  16.             aesAlg.Key = Key;  
  17.             aesAlg.IV = IV;  
  18.             ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);  
  19.    
  20.             using (MemoryStream msDecrypt = new MemoryStream(cipherText))  
  21.             {  
  22.                 CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);  
  23.                 byte[] tempbuffer = new byte[cipherText.Length];  
  24.                 int totalBytesRead = csDecrypt.Read(tempbuffer, 0, tempbuffer.Length);  
  25.                 buffer = tempbuffer.Take(totalBytesRead).ToArray();  
  26.             }  
  27.         }  
  28.     }  
  29.     catch (Exception ex)  
  30.     {  
  31.    
  32.     }  
  33.     finally  
  34.     {  
  35.         if (aesAlg != null)  
  36.             aesAlg.Clear();  
  37.     }  
  38.     return buffer;  

客户端加密解密文本文件实战:

 
  1. /// <summary> 
  2. /// 加密解密  
  3. /// </summary> 
  4. private static void _EncryptAndDecrypt()  
  5. {  
  6.     ASCIIEncoding asciiEnc = new ASCIIEncoding();  
  7.     byte[] initVectorBytes = asciiEnc.GetBytes("@1B2c3D4e5F6g7H8");  
  8.    
  9.     //Randomly generate or Book key - key K2 - Key to encrypt xml content  
  10.     string keyK2 = Generator.RandomString(10);  
  11.     //Generate the 128 bit string using MD5 for key K2  
  12.     MD5 hashProvider = MD5.Create();  
  13.     byte[] md5EncryptedKeyK2 = hashProvider.ComputeHash(asciiEnc.GetBytes(keyK2));  
  14.    
  15.     string filename = "NewTextDocument.txt";  
  16.     string filepath = Environment.CurrentDirectory + "" + filename;  
  17.    
  18.     byte[] Content = Encryption.encryptStringToBytes_AES(File.ReadAllBytes(filepath), md5EncryptedKeyK2, initVectorBytes);  
  19.     string encryptfilepath = Environment.CurrentDirectory + "encrypt" + filename;  
  20.     File.WriteAllBytes(encryptfilepath, Content);  
  21.    
  22.     byte[] decryptContent = Encryption.decryptBytes(File.ReadAllBytes(encryptfilepath), md5EncryptedKeyK2, initVectorBytes);  
  23.     string decryptfilepath = Environment.CurrentDirectory + "decrypt" + filename;  
  24.     File.WriteAllBytes(decryptfilepath, decryptContent);  
  25.    

压缩解压:

 
  1. string filename = "NewTextDocument.txt";  
  2. string filepath = Environment.CurrentDirectory + "" + filename;  
  3. string zipfilepath = Environment.CurrentDirectory + "NewTextDocument.zip";  
  4. using (ZipFile contentZip = new ZipFile())  
  5. {  
  6.     //压缩  
  7.     contentZip.AlternateEncoding = Encoding.GetEncoding("iso-8859-1");  
  8.     contentZip.AlternateEncodingUsage = ZipOption.Always;  
  9.     ZipEntry contentFile = contentZip.AddEntry(filename, File.ReadAllBytes(filepath));  
  10.     contentZip.Save(zipfilepath);  
  11.    
  12.    
  13.     //解压  
  14.     contentZip.ExtractAll(Environment.CurrentDirectory);  

压缩加密解密解压:

 
  1. string filename = "NewTextDocument.zip";  
  2.    
  3.            string filepath = Environment.CurrentDirectory + "" + filename;  
  4.            string zipfilepath = Environment.CurrentDirectory + "" + filename;  
  5.    
  6.            ZipFile contentZip = new ZipFile();  
  7.    
  8.            contentZip.AlternateEncoding = Encoding.GetEncoding("iso-8859-1");  
  9.            contentZip.AlternateEncodingUsage = ZipOption.Always;  
  10.            var bytecontent = File.ReadAllBytes(Environment.CurrentDirectory + "NewTextDocument.txt");  
  11.            ZipEntry contentFile = contentZip.AddEntry("NewTextDocument.txt", bytecontent);  
  12.            contentZip.Save(zipfilepath);  
  13.    
  14.            ASCIIEncoding asciiEnc = new ASCIIEncoding();  
  15.            byte[] initVectorBytes = asciiEnc.GetBytes("@1B2c3D4e5F6g7H8");  
  16.    
  17.            //Randomly generate or Book key - key K2 - Key to encrypt xml content  
  18.            string keyK2 = Generator.RandomString(10);  
  19.            //Generate the 128 bit string using MD5 for key K2  
  20.            MD5 hashProvider = MD5.Create();  
  21.            byte[] md5EncryptedKeyK2 = hashProvider.ComputeHash(asciiEnc.GetBytes(keyK2));  
  22.    
  23.            byte[] Content = Encryption.encryptStringToBytes_AES(File.ReadAllBytes(filepath), md5EncryptedKeyK2, initVectorBytes);  
  24.            string encryptfilepath = Environment.CurrentDirectory + "encrypt" + filename;  
  25.            File.WriteAllBytes(encryptfilepath, Content);  
  26.    
  27.            byte[] decryptContent = Encryption.decryptBytes(File.ReadAllBytes(encryptfilepath), md5EncryptedKeyK2, initVectorBytes);  
  28.            string decryptfilepath = Environment.CurrentDirectory + "decrypt" + filename;  
  29.            File.WriteAllBytes(decryptfilepath, decryptContent);  
  30.    
  31.     __箰讆__1360__璺拶__      contentZip.ExtractAll(Environment.CurrentDirectory + "unzipdecrypt");  
  32.            string key = Convert.ToBase64String(md5EncryptedKeyK2);  
  33.            string iv = Convert.ToBase64String(initVectorBytes);  
  34.            Console.WriteLine(key);  
  35.            Console.WriteLine(iv);  
  36.    
  37.            byte[] decryptContent1 = Encryption.decryptBytes(File.ReadAllBytes(encryptfilepath), Convert.FromBase64String(key), Convert.FromBase64String(iv));  
  38.            string decryptfilepath1 = Environment.CurrentDirectory + "decrypt1" + filename;  
  39.    
  40.            contentZip.ExtractAll(Environment.CurrentDirectory + "unzipdecrypt1");  
  41.    
  42.            File.WriteAllBytes(decryptfilepath1, decryptContent1); 

 

关注我们

最新资讯离线随时看 聊天吐槽赢奖品