随笔 - 13, 文章 - 0, 评论 - 1, 引用 - 0
数据加载中……

加密解密

using System;
using System.Collections.Generic;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.IO;

/// <summary>
///Encrypt 的摘要说明
/// </summary>
public class Encrypt
{


    //cookies加密密钥  
    public static string DES_Key = "12345678";

    #region DESEnCode DES加密
    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="pToEncrypt"></param>
    /// <returns></returns>
    public static string DESEnCode(string pToEncrypt)
    {
        pToEncrypt = HttpContext.Current.Server.UrlEncode(pToEncrypt);
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);


        des.Key = ASCIIEncoding.ASCII.GetBytes(DES_Key);
        des.IV = ASCIIEncoding.ASCII.GetBytes(DES_Key);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();

        StringBuilder ret = new StringBuilder();
        foreach (byte b in ms.ToArray())
        {
            ret.AppendFormat("{0:X2}", b);
        }
        ret.ToString();
        return ret.ToString();
    }
    #endregion

    #region DESDeCode DES解密
    /// <summary>
    /// 解密
    /// </summary>
    /// <param name="pToDecrypt"></param>
    /// <returns></returns>
    public static string DESDeCode(string pToDecrypt)
    {
        try
        {
            //    HttpContext.Current.Response.Write(pToDecrypt + "<br>" + sKey);  
            //    HttpContext.Current.Response.End();  
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            des.Key = ASCIIEncoding.ASCII.GetBytes(DES_Key);
            des.IV = ASCIIEncoding.ASCII.GetBytes(DES_Key);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            StringBuilder ret = new StringBuilder();

            return HttpContext.Current.Server.UrlDecode(System.Text.Encoding.Default.GetString(ms.ToArray()));
        }
        catch (Exception)
        {

            return "";
        }

    }
    #endregion

 

 

 

 

 

}

posted on 2013-06-03 11:33 李鑫 阅读(307) 评论(0)  编辑 收藏 引用 所属分类: C#


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理