Encrypt passwords using ASP.net

Source: Internet
Author: User
Tags md5 sha1
asp.net| encryption

In ASP, no encrypted objects are provided, we can only use external objects for encryption. Now it's okay to provide a solution for encryption in asp.net. A class FormsAuthentication is included in the namespace System.Web.Security, which has a method hashpasswordforstoringinconfigfile. This method can turn user-supplied characters into garbled, then store them, and can even be stored in cookies.

The HashPasswordForStoringInConfigFile method is simple to use, and it supports the "SHA1" and "MD5" cryptographic algorithms.

The following code is a simple demonstration of its usage:

<%@ Page language= "C #"%>
<%@ Import namespace= "System.Web.Security"%>
<script language= "C #" runat= "Server" >
public void encryptstring (Object sender, EventArgs e)
{
SHA1. Text = FormsAuthentication.HashPasswordForStoringInConfigFile (txtPassword.Text, "SHA1");
MD5. Text =formsauthentication.hashpasswordforstoringinconfigfile (txtPassword.Text, "MD5");
}
</script>
<body>
<form runat= "Server" id= "Form1" >
<p>
<b>original Clear Text Password: </b>
<br>
<asp:textbox id= "Txtpassword" runat= "Server"/>
<asp:button runat= "Server" text= "Encrypt String" id= "Button1"/>
</p>
<p>
<b>encrypted Password in SHA1: </b>
<asp:label id= "SHA1" runat= "Server"/>
</p>
<p>
<b>encrypted Password in MD5: </b>
<asp:label id= "MD5" runat= "Server"/>
</p>
</form>
</body>

As you can see, this is simple and easy to use. We can encapsulate this encryption program in a function that is easy to reuse. The code is as follows:

public string Encryptpassword (String passwordstring,string passwordformat)
{
if (passwordformat= "SHA1") {
Encryptpassword=formsauthortication.hashpasswordforstoringinconfigfile (passwordstring, "SHA1");
}
ElseIf (passwordformat= "MD5")
{Encryptpassword=formsauthortication.hashpasswordforstoringinconfigfile (passwordstring, "MD5");
}
Else
{
Encryptpassword= "";
}




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.