c#.net下的加密例子

来源:互联网 发布:软件数据线 安卓 编辑:程序博客网 时间:2024/04/25 22:22

引用:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

sha1:

 string strText = this.TextBox1.Text;
        string EncryptPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(strText, "SHA1");
        this.TextBox2.Text = EncryptPassword;

md5:

 string strText = this.TextBox1.Text;
        string EncryptPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(strText, "MD5");
        this.TextBox2.Text = EncryptPassword;

des:

 //des加密
  public static string Encode(string data)
  {
   byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
   byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

   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();
   return Convert.ToBase64String(ms.GetBuffer(),0,(int)ms.Length);
  
  }

  public static string Decode(string data)
  {  
   byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
   byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

   byte[] byEnc;
   try
   {
    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();
  }

原创粉丝点击