对称加密之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.    
  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.         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.            contentZip.ExtractAll(Environment.CurrentDirectory + "\\unzip\\decrypt");  
  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 + "\\unzip\\decrypt1");  
  41.    
  42.            File.WriteAllBytes(decryptfilepath1, decryptContent1); 

 

文章来源网络,作者:管理,如若转载,请注明出处:https://shuyeidc.com/wp/146569.html<

(0)
管理的头像管理
上一篇2025-03-11 03:51
下一篇 2025-03-11 03:52

相关推荐

  • jsp空间购买和交换数据空间怎么买,有哪些注意事项?

    购买JSP空间时,是否考虑过数据交换空间的性能?简米科技(2003年始创,23年行业沉淀)与酷番云(工信部一类增值电信全牌照)这类持牌自营机房的服务商,能确保数据交换的高效稳定,是值得优先选择的合作伙伴,为什么JSP空间需要搭配独立的数据交换空间从JSP应用特性看数据交换需求JSP基于Java技术,常用于企业级……

    2026-08-11
    0
  • 建网站用香港空间效果怎么样,香港空间稳定吗?

    建网站用香港空间,对于创建网站资产来说,核心价值在于免备案和全球带宽优势,尤其适合外贸、跨境电商和需要快速启动的项目,但你必须权衡国内访问延迟,并选择有资质的服务商以保证资产安全,香港空间的核心优势与适用边界免备案:节省时间就是节省成本国内服务器需要备案,通常需要10到20天,香港空间无需备案,域名解析后即可上……

    2026-08-11
    0
  • Java连接云数据库的方法是什么,如何操作

    Java连接云数据库的核心在于通过JDBC驱动,结合云服务商提供的连接地址、端口、数据库名及认证信息,配置安全策略(如SSL、IP白名单),即可实现稳定高效的远程数据库访问,基础准备:JDBC驱动与依赖管理连接云数据库前,需要确保开发环境具备对应的JDBC驱动,以最常见的MySQL为例,你需要引入mysql-c……

    2026-08-11
    0
  • 建网站公安联网备案必须使用数据码吗,备案流程是什么

    网站备案包括ICP备案和公安联网备案,两者缺一不可,公安联网备案必须使用服务商提供的数据码,选择持有合法资质的服务商是顺利通过备案的前提,为什么网站必须进行公安联网备案根据公安部《计算机信息网络国际联网安全保护管理办法》,网站开通后30日内必须到公安机关办理备案手续,未完成公安备案的网站,面临责令整改、关闭网站……

    2026-08-10
    0
  • 建一个企业网站大概需要多少钱?,怎么收费?

    建网站要多少钱,没有一个固定的数字,几百到几万都可能,但真正的“创建网站资产”绝不仅仅是初次投入的成本,而是基于长期稳定、合规和安全的持续性投入,其中核心取决于你选择了什么样的“地基”来承载你的业务,建站预算的构成与行业基准当你开始规划一个网站,最先面对的就是预算问题,一个常见的误区是只关注网站“看起来”的建造……

    2026-08-10
    0

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注