2015年5月24日 星期日

C# 加密解密

參考資料: http://www.dotblogs.com.tw/jaigi/archive/2013/05/20/104563.aspx

using System.Text;
using System.Security.Cryptography;
using System.IO;
-------------------------------------------------------------





public static string strKey = "12345678";
    public static string strIV = "87654321";

    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="_strQ"></param>
    /// <returns></returns>
    public static string Encrypt(string _strQ)
    {
        byte[] buffer = Encoding.UTF8.GetBytes(_strQ);
        MemoryStream ms = new MemoryStream();
        DESCryptoServiceProvider tdes = new DESCryptoServiceProvider();
        CryptoStream encStream = new CryptoStream(ms, tdes.CreateEncryptor(Encoding.UTF8.GetBytes(strKey), Encoding.UTF8.GetBytes(strIV)), CryptoStreamMode.Write);
        encStream.Write(buffer, 0, buffer.Length);
        encStream.FlushFinalBlock();
        return Convert.ToBase64String(ms.ToArray()).Replace("+", "%");
    }
    /// <summary>
    /// 解密
    /// </summary>
    /// <param name="_strQ"></param>
    /// <returns></returns>
    public static string Decrypt(string _strQ)
    {
        _strQ = _strQ.Replace("%", "+");
        byte[] buffer = Convert.FromBase64String(_strQ);
        MemoryStream ms = new MemoryStream();
        DESCryptoServiceProvider tdes = new DESCryptoServiceProvider();
        CryptoStream encStream = new CryptoStream(ms, tdes.CreateDecryptor(Encoding.UTF8.GetBytes(strKey), Encoding.UTF8.GetBytes(strIV)), CryptoStreamMode.Write);
        encStream.Write(buffer, 0, buffer.Length);
        encStream.FlushFinalBlock();
        return Encoding.UTF8.GetString(ms.ToArray());
    }

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁