ASP.NET中密碼保護,MD5和SHA1算法的使用
2024-07-10 12:58:20
供稿:網友
 
你的主頁或者你管理的網站有各種密碼需要保護,把密碼直接放在數據庫或者文件中存在不少安全隱患,所以密碼加密后存儲是最常見的做法。在asp.net中實現加密非常容易。.net sdk中提供了cookieauthentication類,其中的hashpasswordforstoringinconfigfile方法可直接使用md5和sha1算法。例子如下:
file: encrypting.aspx
<%@ page language="c#" codebehind="encrypting.cs" autoeventwireup="false" inherits="encrypting.encrypting" %>
<html><head>
    <meta name="generator" content="microsoft visual studio 7.0">
    <meta name="code_language" content="c#"></head>
  <body>
 
    <form method="post" runat="server">
<p> </p>
<p>
<asp:textbox id=textbox1 runat="server"></asp:textbox>
<asp:button id=button1 runat="server" text="encrypting"></asp:button></p>
<p>encrypting password(md5):
<asp:label id=md5 runat="server"></asp:label></p>
     </form>
 
  </body></html>
file:encrypting.cs
namespace encrypting
{
    using system;
    using system.collections;
    using system.componentmodel;
    using system.data;
    using system.drawing;
    using system.web;
    using system.web.sessionstate;
    using system.web.ui;
    using system.web.ui.webcontrols;
    using system.web.ui.htmlcontrols;
    using system.web.security;
    /// <summary>
    ///    summary description for encrypting.
    /// </summary>
    public class encrypting : system.web.ui.page
    {
  protected system.web.ui.webcontrols.label md5;
  protected system.web.ui.webcontrols.button button1;
  protected system.web.ui.webcontrols.textbox textbox1;
 
 public encrypting()
 {
     page.init += new system.eventhandler(page_init);
        }
        protected void page_load(object sender, eventargs e)
        {
            if (!ispostback)
            {
                //
                // evals true first time browser hits the page
                //
            }
        }
        protected void page_init(object sender, eventargs e)
        {
            //
            // codegen: this call is required by the asp+ windows form designer.
            //
            initializecomponent();
        }
        /// <summary>
        ///    required method for designer support - do not modify
        ///    the contents of this method with the code editor.
        /// </summary>
        private void initializecomponent()
  {
   button1.click += new system.eventhandler (this.button1_click);
   this.load += new system.eventhandler (this.page_load);
  }
  public void button1_click (object sender, system.eventargs e)
  {
   md5.text = cookieauthentication.hashpasswordforstoringinconfigfile(textbox1.text,"md5");
   //sha1 use cookieauthentication.hashpasswordforstoringinconfigfile(textbox1.text,"sha1");
  }
    }
}
注意:類cookieauthentication的namespace是system.web.security。