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。