对称加密之AES及压缩加密解密解压综合实战

12-22

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

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

对称加密之AES及压缩加密解密解压综合实战

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

加密实现代码:

  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. aesAlg.Padding = PaddingMode.PKCS7;
  16. aesAlg.Key = Key;
  17. aesAlg.IV = IV;
  18. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
  19. msEncrypt = new MemoryStream();
  20. using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
  21. {
  22. csEncrypt.Write(fileContentBytes, 0, fileContentBytes.Length);
  23. csEncrypt.FlushFinalBlock();
  24. }
  25. }
  26. catch (Exception ex)
  27. {
  28. }
  29. finally
  30. {
  31. if (aesAlg != null)
  32. aesAlg.Clear();
  33. }
  34. return msEncrypt.ToArray();
  35. }

解密代码实现:

  1. public static byte[] decryptBytes(byte[] cipherText, byte[] Key, byte[] IV)
  2. {
  3. if (cipherText == null || cipherText.Length <= 0)
  4. 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. using (MemoryStream msDecrypt = new MemoryStream(cipherText))
  20. {
  21. CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
  22. byte[] tempbuffer = new byte[cipherText.Length];
  23. int totalBytesRead = csDecrypt.Read(tempbuffer, 0, tempbuffer.Length);
  24. buffer = tempbuffer.Take(totalBytesRead).ToArray();
  25. }
  26. }
  27. }
  28. catch (Exception ex)
  29. {
  30. }
  31. finally
  32. {
  33. if (aesAlg != null)
  34. aesAlg.Clear();
  35. }
  36. return buffer;
  37. }

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

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

压缩解压:

  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. contentZip.ExtractAll(Environment.CurrentDirectory);
  13. }

压缩加密解密解压:

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