5,692,513 members and growing! (16,184 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Howto     Intermediate

Creating CAPTCHA-Like Functionality in ASP.NET

By azamsharp

How to create CAPTCHA-like functionality in ASP.NET.
C#, Windows, .NET, Visual Studio, GDI+, ASP.NET, Dev

Posted: 8 Dec 2006
Updated: 8 Dec 2006
Views: 20,040
Bookmarked: 26 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
10 votes for this Article.
Popularity: 3.44 Rating: 3.44 out of 5
3 votes, 30.0%
1
2 votes, 20.0%
2
0 votes, 0.0%
3
2 votes, 20.0%
4
3 votes, 30.0%
5

Introduction

According to Wikipedia, CAPTCHA ("Completely Automated Public Turing test to tell Computers and Humans Apart") is a challenge response test which is used to check if the user is human or not. CAPTCHA is used exclusively in applications where user input is required. These applications include blogs, forums, and portals. In this article, I will demonstrate how to create a simple webpage that uses the CAPTCHA functionality.

The CreateImage Method

The first task is to create an image and put it on the screen. For that, I have created an ASP.NET page named CaptchaControl.aspx. The CaptchaControl.aspx page will be responsible for displaying the image to the user. Let’s take a look at the following code which generates the image:

private void CreateImage()
{

    string code = GetRandomText();
    Bitmap bitmap = new Bitmap(200,150,
           System.Drawing.Imaging.PixelFormat.Format32bppArgb);
    Graphics g = Graphics.FromImage(bitmap);
    Pen pen = new Pen(Color.Yellow);
    Rectangle rect = new Rectangle(0,0,200,150);
    SolidBrush b = new SolidBrush(Color.DarkKhaki);
    SolidBrush blue = new SolidBrush(Color.Blue);
    int counter = 0;
    g.DrawRectangle(pen, rect);
    g.FillRectangle(b, rect);

    for (int i = 0; i < code.Length; i++)
    {
        g.DrawString(code[i].ToString(), 
           new Font("Verdena", 10 + rand.Next(14, 18)), 
           blue, new PointF(10 + counter, 10));
        counter += 20;
    }

    DrawRandomLines(g);
    Response.ContentType = "image/gif";
    bitmap.Save(Response.OutputStream,ImageFormat.Gif);
    g.Dispose();
    bitmap.Dispose();

}

There is a bunch of stuff going on inside the CreateImage method. The GetRandomText method generates the random text and returns to the caller. If you are unfamiliar with creating random strings, then I would suggest that you check out my article: Creating Random Passwords. After I create the Rectangle where the text would appear, I resize the text to give it a strange look. Finally, I call the DrawRandomLines method which protects the image from OCR software.

The GetRandomText Method

The purpose of the GetRandomText method is to generate a random text every time a user gets the old text wrong. Take a look at the simple method which returns the random text.

private string GetRandomText()
{

    StringBuilder randomText = new StringBuilder();

    if (Session["Code"] == null)
    {

        string alphabets = "abcdefghijklmnopqrstuvwxyz";
        Random r = new Random();

        for (int j = 0; j <= 5; j++)
        {
            randomText.Append(alphabets[r.Next(alphabets.Length)]);
        }
        Session["Code"] = randomText.ToString();
    }
    return Session["Code"] as String;
}

The DrawRandomLines Method

The DrawRandomLines method puts the lines on the text which is displayed on an image. The purpose of these lines is to make it difficult for the bots to read the text. This way the text can only be read by humans.

private void DrawRandomLines(Graphics g)
{
    SolidBrush green = new SolidBrush(Color.Green);

    for (int i = 0; i < 20; i++)
    {
        g.DrawLines(new Pen(green, 2), GetRandomPoints());
    }

}

private Point[] GetRandomPoints()
{

    Point[] points = { new Point(rand.Next(10, 150), 
                       rand.Next(10, 150)), 
                       new Point(rand.Next(10, 100), 
                       rand.Next(10, 100)) };
    return points;
}

Using the CAPTCHA Page

We have created the CAPTCHA feature, but the question is how do we use it. In order to use the CAPTCHA feature, you will need to create a page which consumes the CaptchaControl.aspx page. I have created the Default.aspx page which uses the CaptchaControl.aspx as the ImageUrl to the ASP.NET Image control. Check out the complete HTML code of the Default.aspx page.

<form id="form1" runat="server">
<div>
<asp:Image ID="myImage" runat="server" 
     ImageUrl="~/CaptchaControl.aspx" />
<br />
<br />
Enter code: <asp:TextBox ID="TextBox1" runat="server">
            </asp:TextBox>
<asp:Button ID="Button1" runat="server" 
     Text="Validate" OnClick="Button1_Click" />
<br />
<br />
<asp:Label ID="lblError" runat="server" Font-Bold="True" 
     Font-Size="X-Large" ForeColor="Red"></asp:Label></div>
</form>

The important thing to note is the ASP.NET Image control which requests the CaptchaControl.aspx page and generates the image. The code for the validation of the user text against the CAPTCHA text is pretty simple, and you can view it in the downloaded files.

Below is an image of how the application looks like:

Conclusion

In this article, I demonstrated how easy it is to create a CAPTCHA feature. This feature can play a very important role in the security of a web application.

I hope you liked the article, happy programming!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

azamsharp


I am the founder of knowledge base website, HighOnCoding, GridViewGuy, RefactorCode.com and ScreencastADay.com.

HighOnCoding is a website which will get you high legally with useful information. There are tons of articles, videos and podcasts hosted on HighOnCoding.

ScreencastADay is a website committed to educate you everyday. The idea of the website is really simple. We believe that in order to be successful you need to learn something new everyday. ScreencastADay puts this thought into action by providing new screencast every day. This means you will get 7 screencasts a week and 365 screencasts a year unless of course it is a leap year in that case you get one more bonus screencast.

HighOnCoding.com www.HighOnCoding.com

ScreencastADay.com: www.ScreencastADay.com

RefactorCode: www.RefactorCode.com

GridViewGuy: GridViewGuy

My Blog:

Blog

Occupation: Web Developer
Location: United States United States

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 10 of 10 (Total in Forum: 10) (Refresh)FirstPrevNext
GeneralIs there a ASP.NET VB version floating around?memberprojecthiphop14:33 27 Jun '07  
GeneralThank youmembercykophysh394:59 25 Feb '07  
GeneralEnhancementmemberjcvest9:06 26 Dec '06  
GeneralRe: Enhancementmembercykophysh394:53 25 Feb '07  
GeneralA good start for a captiva, but as coded can easily be brokenmemberrweil13:33 12 Dec '06  
GeneralRe: A good start for a captiva, but as coded can easily be brokenmemberazamsharp13:37 12 Dec '06  
GeneralRe: A good start for a captiva, but as coded can easily be brokenmembercykophysh394:57 25 Feb '07  
GeneralStoring in sessionmemberMartin N.0:55 11 Dec '06  
GeneralRe: Storing in sessionmemberazamsharp13:12 11 Dec '06  
GeneralRe: Storing in sessionmemberMartin N.20:22 12 Dec '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 8 Dec 2006
Editor: Smitha Vijayan
Copyright 2006 by azamsharp
Everything else Copyright © CodeProject, 1999-2008
Web10 | Advertise on the Code Project