In ASP, encryption objects are not provided. We can only use external objects for encryption. Now, the encryption solution is provided in ASP. NET. The namespace system. Web. Security contains the formsauthentication class. There is a method hashpasswordforstoringinconfigfile. This method can convert the characters provided by the user into garbled characters, store them, and even store them in cookies.
Hashpasswordforstoringinconfigfile is easy to use. It supports "sha1" and "MD5" encryption algorithms.
The following code demonstrates its usage in a simple way:
<% @ Page Language = "C #" %>
<% @ Import namespace = "system. Web. Security" %>
<HTML>
<Head>
<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>
</Head>
<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" onclick = "encryptstring" 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>
</Html>
As you can see, this is easy to use. We can encapsulate this encryption program in a function to facilitate repeated use. 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 = "";
}
We can add a field to the database and use insert to store the encrypted password into the database as a string. When a user logs in, he/she can compare the password encryption result entered by the user with the correct result in the database. This method is used to verify the correctness of the password.