ASP. NET verification code technology (C #)

Source: Internet
Author: User
Tags arabic numbers
Course description

Hello everyone, in the last course, we started to learn howASP. NETGraph programming technology. Today, we have a deep understanding of the verification code technology.ASP. NET.

Verification code technology is currently widely usedWebProgramA security defense technology. When logging on, the system not only outputs the user name and password, but also enters a randomly generated Verification Code text. At this time, the user needs to correctly enter these three information before logging on to the system.

Because the verification code technology can effectively defend against certain hacker attacks, it has been widely used in someC/SThis source is also used in the systemWebDeveloped technology.

Verification Code principle

In the current software operating environment, security has become an issue that must be considered by most software. hackers are everywhere and attack methods are increasingly diverse, especiallyWebBecause of its openness, the system is facing a severe test. As hacker events emerge in an endless stream, the loss and impact of the system continue to increase, in this regard, our software developers need to have a considerable understanding of this and take measures to defend against various hacker attacks.

Enumeration dictionary security attack

In various hacker attacks, it is common to use usernames and passwords. Many of them use enumeration dictionaries to continuously test user names and passwords.

For example, a hacker obtains a bank account and opens the online banking logon interface of the Account's bank. AnalyzeHtmlCodeIt is found that the page is shoddy, with no verification code and no security control. You only need to enter the bank account and withdrawal password to log on. The hacker immediately wrote a program and called it directly.HTTPProtocol, use a program to simulate a browser to submit an account and password to the online banking server to try to log on. Because the withdrawal password is6As a result, there are 1 million combinations of Arabic numbers. The Hacker's computer has been tested from six to six, which will certainly test the real password. The hacker finds a computer with high-speed broadband access and runs the program for obtaining the withdrawal password.1Test in seconds10Password, so the cost10The password can be found in seconds.10Tens of thousands of seconds.27Hours, more than one day, in fact, it may not take that long. The hacker turned around and found that the password had been found, so he immediately logged on to the online bank to get the money, or forged a bank card.ATMWithdraw cash from the machine. That is to say, it takes up to one day for hackers to obtain an unpredictable amount of illegal income.

Verification Code defense

Online Banking can be used to defend against hacker attacks, suchActiveXControl in place of the standard text box to enter the account and password, you can useUSBOr use a client program instead of a browser to log on to the online bank. However, these are client technologies, and thousands of hackers can perform a variety of surgical knives to dissect these technologies. Basically, the client technology is unreliable.

It is relatively safer to use server-side technology. For example, the password is found to be consecutively incorrect.3The account is locked once,1You can use the verification code technology to defend against enumeration dictionary password attacks.

There is a new online bank, which is similar to the old online bank, but the verification code technology is adopted. When a user logs on, in addition to entering the account and withdrawal password, the browser also displays an image, some scrawled characters are displayed. You need to recognize these characters before entering them. When submitting a form to the server, the browser will append the verification code entered by the user, after the Server accepts the form data, in addition to verifying the account and withdrawal password, it also checks whether the verification code is entered correctly. If the login information verification fails, the server will prompt you to log on again, in addition, a new verification code containing random content is generated, and the user has to re-identify the new verification code during the next logon.

Because the correct Verification Code text is stored on the server, the hacker program on the client cannot obtain it, the content of the verification code is random, and the hacker program cannot find the rule, you can only obtain the verification code by recognizing the image containing the verification code sent from the server. This shows the difference between the computer and the human brain. The human brain far exceeds the current computer in terms of graphic recognition, and the server uses some techniques to generate sloppy writing, the human brain can easily recognize images filled with random distribution, but computers are hard to recognize. The hacker program cannot recognize the verification code. Only images can be displayed for the hacker to personally identify the verification code. In this case, each time the hacker tests the password, the hacker must carefully identify the verification code image and then manually enter the verification code text. A maximum of 1 million input requests are required. It is estimated that no one in the world will be willing to do this kind of work. In this way, the verification code technology effectively defends against this enumeration dictionary Test password security attack. At this time, hackers will turn to other methods, and a large number of novice hackers will give up attacking the website.

Verification code technical concept

The verification code technology utilizes the difference between the human brain and the computer.

We all know that there is a big difference between computers and the human brain. Computers are competent for numerical computation and precise logic judgment. They are suitable for executing repetitive and repetitive simple data processing, but image recognition, fuzzy logic judgment, poor learning and innovation capabilities. The opposite is true for the human brain, but not for numerical operations, but for image recognition.

In the verification code technology, a key process is to identify the verification code text from an image filled with random shapes. This process is hard to be achieved by computers at present, it is quite easy for the human brain.

The verification code technology forces the human brain to participate in the Security Information verification process by using images that are difficult to recognize by computers and easy to recognize by the human brain. The image that contains the verification code text is the verification code medium. After careful observation, we can know that this verification code media is easy to recognize by computers, so we can also use other means such as synthetic speech as the verification code media. For example, the server providesQqAdd noise to the emoticons, and then let the user determine whether to choose the emoticons of the image, whether it is a smile or a nosebleed, which can also be used as a verification code.

Because enumeration dictionary security attacks require a large number of attempts to guess the security information, the repetitive process may require tens of thousands or even hundreds of millions of times. The verification code technology forces the human brain to participate in every attempt to guess the security information, it is difficult for the human brain to perform simple repetitive work for a long time, which makes enumeration dictionary security attacks unfeasible. In this way, the application successfully defends against enumeration dictionary security attacks.

ASP. NETUsing Verification Code Technology

In the verification code technology, the server program needs to create a verification code image, which uses graphical programming. Therefore, this course is stillC #A series of Graphic programming tutorials on Discovery journey.

Based on the Verification Code principle, we useC #InASP. NETThe verification code function is implemented.

Checkimage. aspx

First, based on the content of the previous course, we will create an image service page to provide images containing Verification Code text.Checkimage. aspx. ItsHtmlThe code is very simple. There is only one line and NO content is output. In itsPage_loadThe process of creating a verification code image.

// Create a verification code text containing random content
System. Random Rand =NewRandom ();
Int Len = Rand. Next (4, 6 );
Char [] Chars ="0123456789 abcdefghijklmnopqrstuvwxyz". Tochararray ();
System. Text. stringbuilder mystr =NewSystem. Text. stringbuilder ();
For (IntIcount = 0; icount <Len; icount ++)
{
Mystr. append (chars [Rand. Next (chars. Length)]);
}
String TEXT = mystr. tostring ();
// Save the verification code to the session for other modules to use
This . Session ["Checkcode"] = Text;
Size imagesize = size. empty;
Font myfont =NewFont ("Ms sans serif", 20 );
// Calculate the image size of the Verification Code
Using (Bitmap BMP =NewBitmap (10, 10 ))
{
Using(Graphics G = graphics. fromimage (BMP ))
{
Sizef size = G. measurestring (text, myfont, 10000 );
Imagesize. width = (Int) Size. Width + 8;
Imagesize. Height = (Int) Size. height + 8;
}
}
// Create a verification code Image
Using (Bitmap BMP =NewBitmap (imagesize. Width, imagesize. Height ))
{
// Draw the verification code text
Using(Graphics G = graphics. fromimage (BMP ))
{
G. Clear (color. White );
Using(Stringformat F =NewStringformat ())
{
F. Alignment = stringalignment. Near;
F. linealignment = stringalignment. Center;
F. formatflags = stringformatflags. nowrap;
G. drawstring (
Text,
Myfont,
Brushes. Black,
NewRectanglef (
0,
0,
Imagesize. Width,
Imagesize. Height ),
F );
}// Using
}// Using
// Make noise and noise points out of 30% of the Image Area
IntNum = imagesize. Width * imagesize. Height * 30/100;
For(IntIcount = 0; icount <num; icount ++)
{
// Set the image pixel with random color at random positions
IntX = Rand. Next (imagesize. width );
IntY = Rand. Next (imagesize. Height );
IntR = Rand. Next (255 );
IntG = Rand. Next (255 );
IntB = Rand. Next (255 );
Color c = color. fromargb (R, G, B );
BMP. setpixel (X, Y, C );
}//
// Output image
System. Io. memorystream MS =NewSystem. Io. memorystream ();
BMP. Save (MS, system. Drawing. imaging. imageformat. PNG );
This. Response. contenttype ="Image/PNG";
Ms. writeto (This. Response. outputstream );
Ms. Close ();
}// Using
Myfont. Dispose ();

First, we use. NetRandom number generator in the frameworkRandomType to generate a variable length text containing random numbers and English characters. This is the original text of the verification code.Session.

Then we create a temporary image, create a temporary image Drawing Object accordingly, and then callGraphicsOfMeasurestringFunction to obtain the display size of this string. Then we can calculate the size of the Verification Code image.

Create a bitmap object, create a drawing object, and then callDrawstringThe function draws the verification code text on this bitmap.

After the verification code is drawn, we randomly create a noise on the image to confuse the image content. The area occupied by these miscellaneous points30%And the positions and colors are random. These miscellaneous can seriously interfere with the program to identify the verification code text. However, when recognizing texts, the human brain can easily eliminate such interference.

After the image is generated, the page is used.PNGFormat.

Checkimage. aspxA static function is provided to check the verification code.

/// <Summary>
/// Check whether the specified text matches the verification code
/// </Summary>
/// <Param name = "text"> Text to be judged </Param>
/// <Returns> Matching or not </Returns>
Public Static BoolCheckcode (StringText)
{
StringTXT = system. Web. httpcontext. Current. session ["Checkcode"]As String;
ReturnTEXT = txt;
}

The code is simple. Is to see if the text passed in by the parameter is equalSessionThe verification code text saved in. Other page programs call this function to verify the verification code.

Login. aspx

After the verification code Image Service Page is complete, we can use this page to implement the verification code technology. Create a Simulated System logon page.

Enter the user name, password, and verification code in the text input box above. An image is placed behind the verification code input box, and the image is fromCheckimage. aspxPage. Enter the three information and click OK to log on. The server segment code that runs the button.

Private VoidCmdok_click (ObjectSender, system. eventargs E)
{
StringUsername =This. Txtusername. text;
StringPassword =This. Txtpassword. text;
StringCheckcode =This. Txtcheckcode. text;
If(Username ="James"
& Password ="ABC"
& Checkimage. checkcode (checkcode ))
{
This. Lblresult. Text ="<B> logon successful </B>";
This. Registerstartupscript ("","<SCRIPT> alert ('logon successful '); </SCRIPT>");
}
Else
{
This. Lblresult. Text ="<Font color = Red> <B> the user logon information is incorrect. enter a new one. </B> </font>";
}
}

In this Code, the program obtains the user name, password, and verification code entered by the user, then judges whether the user name and password are correct, and also callsCheckimageStatic FunctionsCheckcodeTo determine whether the verification code is correct. If all three information is correct, the logon is successful. Otherwise, the logon fails.

In rare cases, if the verification code image generated by the program is hard to recognize, you need to provide a new verification code image. On the login page, you can double-click the image to update the verification code image. Display the verification code ImageHtmlThe code snippet is

IMG SRC =" checkimage. aspx "
title = 'cannot be seen clearly, double-click an image to change it. '
ondblclick =" this. src = 'checkimage. aspx? Flag = '+ math. random () "
border =" 1 ">

We can see thatOndblclickThe image source is updated in event processing. Here we use a meaninglessFlagPage parameters. This ensures that the browser does not use the locally cached Verification Code image, but downloads the latest Verification Code image.

After double-clicking the image, the browser calls it again.Checkimage. aspxPage, so the verification code text on the server is updated, and the image content is also updated.

Because the correct verification code changes randomly and irregularly every time you try to log on or change the verification code image, the security of the logon page is greatly enhanced. However, this will allow the user to identify and enter the verification code during login, which will reduce the availability of the application. Therefore, whether to use the verification code technology requires multiple trade-offs.

Summary

In this course, we studied the principles of the verification code technology and usedC #InASP. NETThe simple verification code technology is implemented. The verification code technology is a security defense technology, which uses certain graphical programming. In this way, graphics programming is widely used and can provide support for many other technologies.

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.