欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

asp.net中的DES加密解密

程序员文章站 2024-03-13 22:56:10
...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.IO;

namespace XYDWXTWeb
{
    public partial class DES : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //string EnPswdStr = Encode(TextBox2.Text);
            string EnPswdStr = Encode(TextBox2.Text);
            //显示出来   
            TextBox1.Text = EnPswdStr;
        }
        public static string _KEY = "HQDCKEY1";  //**  
        public static string _IV = "HQDCKEY2";   //向量  
        public static string Encode(string data)
        {

            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_KEY);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(_IV);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            string strRet = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
            return strRet;
        }  
        //public static string _KEY = "HQDCKEY1";  //**  
        //public static string _IV = "HQDCKEY2";   //向量  
        //public static string Decode(string data)
        //{

        //    byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_KEY);
        //    byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(_IV);

        //    byte[] byEnc;

        //    try
        //    {
        //        data.Replace("_%_", "/");
        //        data.Replace("-%-", "#");
        //        byEnc = Convert.FromBase64String(data);

        //    }
        //    catch
        //    {
        //        return null;
        //    }

        //    DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        //    MemoryStream ms = new MemoryStream(byEnc);
        //    CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
        //    StreamReader sr = new StreamReader(cst);
        //    return sr.ReadToEnd();
        //} 
    }
}
注:注释掉的为解密方法
相关标签: asp.net