程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> .Net(c#)加密解密之Aes和Des,

.Net(c#)加密解密之Aes和Des,

編輯:C#入門知識

.Net(c#)加密解密之Aes和Des,


.Net(c#)加密解密工具類:

/// <summary>
/// .Net加密解密幫助類
/// </summary>
public class NetCryptoHelper
{
    #region des實現

    /// <summary>
    /// Des默認密鑰向量
    /// </summary>
    public static byte[] DesIv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
    /// <summary>
    /// Des加解密鑰必須8位
    /// </summary>
    public const string DesKey = "deskey8w";
    /// <summary>
    /// 獲取Des8位密鑰
    /// </summary>
    /// <param name="key">Des密鑰字符串</param>
    /// <returns>Des8位密鑰</returns>
    static byte[] GetDesKey(string key)
    {
        if (string.IsNullOrEmpty(key))
        {
            throw new ArgumentNullException("key", "Des密鑰不能為空");
        }
        if (key.Length > 8)
        {
            key = key.Substring(0, 8);
        }
        if (key.Length < 8)
        {
            // 不足8補全
            key = key.PadRight(8, '0');
        }
        return Encoding.UTF8.GetBytes(key);
    }
    /// <summary>
    /// Des加密
    /// </summary>
    /// <param name="source">源字符串</param>
    /// <param name="key">des密鑰,長度必須8位</param>
    /// <param name="iv">密鑰向量</param>
    /// <returns>加密後的字符串</returns>
    public static string EncryptDes(string source, string key, byte[] iv)
    {
        using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
        {
            byte[] rgbKeys = GetDesKey(key),
                rgbIvs = iv,
                inputByteArray = Encoding.UTF8.GetBytes(source);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, desProvider.CreateEncryptor(rgbKeys, rgbIvs), CryptoStreamMode.Write))
                {
                    cryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
                    cryptoStream.FlushFinalBlock();
                    // 1.第一種
                    return Convert.ToBase64String(memoryStream.ToArray());

                    // 2.第二種
                    //StringBuilder result = new StringBuilder();
                    //foreach (byte b in memoryStream.ToArray())
                    //{
                    //    result.AppendFormat("{0:X2}", b);
                    //}
                    //return result.ToString();
                }
            }
        }
    }
    /// <summary>
    /// Des解密
    /// </summary>
    /// <param name="source">源字符串</param>
    /// <param name="key">des密鑰,長度必須8位</param>
    /// <param name="iv">密鑰向量</param>
    /// <returns>解密後的字符串</returns>
    public static string DecryptDes(string source, string key, byte[] iv)
    {
        using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
        {
            byte[] rgbKeys = GetDesKey(key),
                rgbIvs = iv,
                inputByteArray = Convert.FromBase64String(source);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, desProvider.CreateDecryptor(rgbKeys, rgbIvs), CryptoStreamMode.Write))
                {
                    cryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
                    cryptoStream.FlushFinalBlock();
                    return Encoding.UTF8.GetString(memoryStream.ToArray());
                }
            }
        }
    }

    #endregion

    #region aes實現

    /// <summary>
    /// Aes加解密鑰必須32位
    /// </summary>
    public static string AesKey = "asekey32w";
    /// <summary>
    /// 獲取Aes32位密鑰
    /// </summary>
    /// <param name="key">Aes密鑰字符串</param>
    /// <returns>Aes32位密鑰</returns>
    static byte[] GetAesKey(string key)
    {
        if (string.IsNullOrEmpty(key))
        {
            throw new ArgumentNullException("key", "Aes密鑰不能為空");
        }
        if (key.Length < 32)
        {
            // 不足32補全
            key = key.PadRight(32, '0');
        }
        if (key.Length > 32)
        {
            key = key.Substring(0, 32);
        }
        return Encoding.UTF8.GetBytes(key);
    }
    /// <summary>
    /// Aes加密
    /// </summary>
    /// <param name="source">源字符串</param>
    /// <param name="key">aes密鑰,長度必須32位</param>
    /// <returns>加密後的字符串</returns>
    public static string EncryptAes(string source, string key)
    {
        using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
        {
            aesProvider.Key = GetAesKey(key);
            aesProvider.Mode = CipherMode.ECB;
            aesProvider.Padding = PaddingMode.PKCS7;
            using (ICryptoTransform cryptoTransform = aesProvider.CreateEncryptor())
            {
                byte[] inputBuffers = Encoding.UTF8.GetBytes(source);
                byte[] results = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length);
                aesProvider.Clear();
                aesProvider.Dispose();
                return Convert.ToBase64String(results, 0, results.Length);
            }
        }
    }
    /// <summary>
    /// Aes解密
    /// </summary>
    /// <param name="source">源字符串</param>
    /// <param name="key">aes密鑰,長度必須32位</param>
    /// <returns>解密後的字符串</returns>
    public static string DecryptAes(string source, string key)
    {
        using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
        {
            aesProvider.Key = GetAesKey(key);
            aesProvider.Mode = CipherMode.ECB;
            aesProvider.Padding = PaddingMode.PKCS7;
            using (ICryptoTransform cryptoTransform = aesProvider.CreateDecryptor())
            {
                byte[] inputBuffers = Convert.FromBase64String(source);
                byte[] results = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length);
                aesProvider.Clear();
                return Encoding.UTF8.GetString(results);
            }
        }
    }

    #endregion
}

調試運行:

class Program
{
    static void Main(string[] args)
    {
        string plainText = "博客園",
            encryptString = NetCryptoHelper.EncryptDes(plainText, NetCryptoHelper.DesKey, NetCryptoHelper.DesIv);

        Console.WriteLine("des加密前的字符串:{0}", plainText);
        Console.WriteLine("des加密後的字符串:{0}", encryptString);
        Console.WriteLine("des解密後的字符串:{0}", NetCryptoHelper.DecryptDes(encryptString, NetCryptoHelper.DesKey, NetCryptoHelper.DesIv));

        Console.WriteLine("-----------分割線-----------");

        Console.WriteLine("aes加密前的字符串:{0}", plainText);
        encryptString = NetCryptoHelper.EncryptAes(plainText, NetCryptoHelper.AesKey);
        Console.WriteLine("aes加密後的字符串:{0}", encryptString);
        Console.WriteLine("aes解密後的字符串:{0}", NetCryptoHelper.DecryptAes(encryptString, NetCryptoHelper.AesKey));
        Console.ReadKey();
    }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved