2014-01-14 12:04

C# AES 加密解密

-C# AES 加密解密-

using System;  
using System.Security.Cryptography;  
using System.Text;  
using System.IO;  
  
namespace GraduationDesign  
{      
  class AESEncryption   
  { 

    //默认密钥向量
    private static byte[] _key1 = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

    /// 
    /// AES加密算法
    /// 
    /// 明文字符串
    /// 密钥
    /// 返回加密后的密文字符串
    public static string AESEncrypt(string plainText, string strKey)
    {
      strKey = Helper.GetMD5(strKey);
      //分组加密算法
      SymmetricAlgorithm des = Rijndael.Create();
      byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组
      //设置密钥及密钥向量
      des.BlockSize = 128;
      des.Mode = CipherMode.ECB;
      des.Padding = PaddingMode.Zeros;
      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 Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);    //密文字节数组转换为字符串
    }

    /// 
    /// AES解密
    /// 
    /// 密文
    /// 密钥
    /// 返回解密后的字符串
    public static string AESDecrypt(string secString, string strKey)
    {
      strKey = Helper.GetMD5(strKey);
      byte[] cipherText = Convert.FromBase64String(secString);    //将密文字符串转换为字节数组
      SymmetricAlgorithm des = Rijndael.Create();
      des.BlockSize = 128;
      des.Mode = CipherMode.ECB;
      des.Padding = PaddingMode.Zeros;
      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 Encoding.UTF8.GetString(decryptBytes);
    }
  }
}
 

你可能还喜欢...

添加新评论