关闭

c#.net下的加密例子

740人阅读 评论(0) 收藏 举报

引用:

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();
  }

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:116770次
    • 积分:1470
    • 等级:
    • 排名:千里之外
    • 原创:52篇
    • 转载:20篇
    • 译文:0篇
    • 评论:5条
    文章分类
    最新评论