AES加解密算法

前言

    在很多项目中,对于安全性的要求是很高的,这就涉及到了各种加密,解密算法,常见的算法有MD5加密、DES加解密、字符串加解密、AES加解密等,下面来一起看一下AES加解密算法。

正文

     AES(Advanced Encryption Standard),又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。AES加密算法速度快,适合大量数据,相对于3DES,又快又安全。

AES加密算法

  //默认密钥向量 
  private static byte[] _key1 = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  //秘钥可以自定义,长度为16位字符
  static string strKey = "dongbinhuiasxiny";//密钥,128位
  /// <summary>
  /// AES加密算法
  /// </summary>
  /// <param name="plainText">明文字符串</param>
  /// <param name="strKey">密钥</param>
  /// <returns>返回加密后的密文字节数组</returns>
     public static byte[] AESEncrypt(string plainText, string strKey)
      {
         //分组加密算法
         SymmetricAlgorithm des = Rijndael.Create();
         byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组
         //设置密钥及密钥向量
         des.Key = Encoding.UTF8.GetBytes(strKey);
         des.IV = _key1;
         MemoryStream ms = new MemoryStream();
         CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
         cs.Write(inputByteArray, 0, inputByteArray.Length);
         cs.FlushFinalBlock();
         byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组
         cs.Close();
         ms.Close();
         return cipherBytes;
     }

AES解密算法

/// <summary>
/// AES解密
/// </summary>
/// <param name="cipherText">密文字节数组</param>
/// <param name="strKey">密钥</param>
/// <returns>返回解密后的字符串</returns>
public static byte[] AESDecrypt(byte[] cipherText, string strKey)
  {
     SymmetricAlgorithm des = Rijndael.Create();
     des.Key = Encoding.UTF8.GetBytes(strKey);
     des.IV = _key1;
     byte[] decryptBytes = new byte[cipherText.Length];
     MemoryStream ms = new MemoryStream(cipherText);
     CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read);
     cs.Read(decryptBytes, 0, decryptBytes.Length);
     cs.Close();
     ms.Close();
     return decryptBytes;
 }

客户端测试

 //AES加密
   string keys = "dongbinhuiasxiny";//密钥,128位   
   string s = "dfererfereerefregrgrgtrytrgrty5hrthyhthtyhttyhjutyjhtyjtyhvfrgtgdfgrtgrbrtyrt12323243455creffefdeddewdwdfwefwevdfvdcvdfgdgrtgdtfgdgref"; //被加密的明文
    byte[] encryptBytes = Secret.AESEncrypt(s, keys);
    s = Convert.ToBase64String(encryptBytes);

 //AES解密
    byte[] decryptBytes = Secret.AESDecrypt(encryptBytes, keys);
    //将解密后的结果转换为字符串,也可以将该步骤封装在解密算法中
    string result = Encoding.UTF8.GetString(decryptBytes); 

总结

    AES加解密算法已经成为对称密钥加密中最流行的算法之一,希望对大家有所帮助,感谢您的阅读。

评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奔跑的大白啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值