程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> asp.net加密

asp.net加密

編輯:.NET實例教程

SHA1算法的散列值大小為160位。一般的加密方式為
byte[] data=System.Text.Encoding.Unicode.GetBytes(source.ToCharArray());
System.Security.Cryptography.SHA1 sha=new System.Security.Cryptography.SHA1CryptoServiceProvider();
byte[] result=sha.ComputeHash(data);
使用SHA1對密碼實現加密,需要使用以下的方法:
string EnPswdStr=System.Web.Security.FormsAuthentication.HashPassWordForStoringInConfigFile(source, "MD5");
或許有的人會問,既然都是采用SHA1方法加密,為什麼對密碼的加密就不能使用原方法呢?因為一般情況下SHA1方法加密出來的密碼並不是常規字符,有些字符甚至無法顯示出來,如果使用這樣的字符作為密碼,在存入數據庫時有些字符會被處理掉,這樣加密結果就會失真,在進行密碼驗證時就會出現無法預料的差錯。而采用密碼加密函數的話就避免了這一個問題,它加密出來的結果都是常規字符,在數據庫進行存儲和程序處理時不會失真。

下面是例子程序:

Default.ASPx
 

 


Code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.ASPx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xHtml1-transitional.dtd">

<html XMLns="http://www.w3.org/1999/xHtml" >
<head runat="server">
    <title>無標題頁</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server"></ASP:Label>
        <br />
        <br />
        <asp:Label ID="Label2" runat="server"></ASP:Label>
        <br />
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></ASP:TextBox>
        <br />
        <input type="submit" />
        </div>
    </form>
</body>
</Html>



Default.ASPx.cs


Code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClIEnt;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            //獲取要加密的字段,並轉化為byte[]數組
            byte[] data = System.Text.Encoding.Unicode.GetBytes(TextBox1.Text.ToCharArray());
        //建立加密服務
            System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            //加密byte[]數組
            byte[] result = sha.ComputeHash(data);
            //將加密後的數組轉化為字符串
            string sResult = System.Text.Encoding.Unicode.GetString(result);
            //顯示出來
            Label1.Text = "SHA1普通加密:" + sResult.ToString() + "<br/>";
            //作為密碼方式加密
            string EnPswdStr = System.Web.Security.FormsAuthentication.HashPassWordForStoringInConfigFile(TextBox1.Text.ToString(), "MD5");
            //顯示出來
            Label2.Text = "SHA1密碼加密:" + EnPswdStr + "<br/>";
        }

    }
}


運行效果圖:


輸入22然後點加密:

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved