CAPTCHA in VB.NetThis is a tutorial on creating a CAPTCHA in VB.NetRate Topic:
2 Votes

This tutorial will guide you through creating a CAPTCHA security image for your web application in VB.Net using Visual Studio 2005. Before we jump into the code lets take a look at what a CAPTCHA is. CAPTCHA stands for Completely Automated Public Turing Test To Tell Computers And Humans Apart." What does this mean? It is a program that can tell humans from machines using some type of generated test. A test most people can easily pass but a computer program cannot. The term CAPTCHA was coined in 2000 by Luis von Ahn, Manuel Blum, Nicholas Hopper and John Langford of Carnegie Mellon University. These 4 individuals are credited with creating the first CAPTCHA, which was used by Yahoo!

CAPTCHA’s have many practical uses for security, including, but not limited to:
1. To prevent “comment spam” in user blogs.
2. Protecting registration at websites (prevents people from having “bots” to register many accounts for the purpose of spam).
3. Protecting email addresses from “Scrapers” (A “Scraper” is a software bot that searches the Internet for email addresses in plain text).
4. Help prevent Dictionary Attacks.

When I first set out to create my own CAPTCHA for a website I was working on for a client, I searched and searched the Internet for a “ready made” one. I found a few simple examples, most done in C# (not that that really matters as I can read/program in both) but I wanted a VB.Net version, which was nowhere to be found. I wanted to offer anyone who used my CAPTCHA more flexibility and control than the simpler versions I had found offered, such as the ability to chose their primary color, secondary color and even the HatchStyle for the HatchBrush. So without further adieu let’s see some code (This is kind of a long class, over 420 lines, so bear with me).

The first thing you must do with the class is to ensure you have the proper references:

For some of these (depends on how you have your IDE setup) you may have to go Project > Add Reference and add a reference to the Namespace’s listed above. After than you need your Global Variables (both property variables and regular global)

Next we need to declare our object properties ( we have Read-only and Read/Write properties). The Read/Write properties (only 1 at this time) is for holding the failure message to the end user if they didn’t type the correct CAPTCHA. This is one of the features I wanted in my version of the CAPTCHA.

The ReadOnly properties are much larger in number, these properties are for:
1. Random string to be displayed
2. The image itself
3. The width of the image
4. The height of the image
5. The main color *
6. The secondary color *
7. The HatchStyle of the HatchBrush *

* These are 3 features I wanted to give the developer control over, a way to customize it for their needs and not be stuck with a version where someone “told” then what to use.

The next step in the class are 2 Enumerations. The first Enum holds the default height and width of the CAPTCHA. I chose to do this with an Enum so if the developer wanted to change the default size he only had to change the dimensions in one place, not multiple. The second Enum holds several HatchStyle’s for the HatchBrush. I only provide 8 at this time but I will be adding more in the future, this way the developer/user of the component isn’t tied into what I said the style should be. Lets take a look at them

Next we need a way to instantiate the object, and finalize & dispose of it when we’re done with it (cleaning up is very important). There are 4 “New()” constructors with this component, which gives you a variety of ways to create a new one. You can create one with just the text to display on the image (all other values will be the default values) all the way to specifying the text, size, font, primary & secondary colors and hatch style. For finalizing we have a Overrides Finalize method, and we have 2 Dispose methods (one is a Overrides utilizing a Boolean “disposing” variable).

In the New() constructors you see 2 methods being called, SetPicSize and SetFont. These 2 methods allow the user of this component to specify both the dimensions of the CAPTCHA and the font to use. With the font, if it’s a font that isn’t installed on the end user’s computer it will default to a System Font (to avoid it bombing on the end user if they don’t have the font the developer specified), and I also suggest you specify a font that is known to be on most, if not all, computers. Lets have a look at those methods.

''' <summary>
''' Method for setting the size of the image
''' </summary>
''' <param name="width">Desired width of the image</param>
''' <param name="height">Desired height of the image</param>
''' <remarks></remarks>
Private Sub SetPicSize(ByVal width As Integer, ByVal height As Integer)
'Check to make sure they didnt supply a width of zero, if they did then throw an exception
If width <= 0 Then Throw New ArgumentOutOfRangeException("width", width, "Argument out of range, must be
greater than zero.")
'Check to make sure they didnt supply a height of zero, if they did then throw an exception
If height <= 0 Then Throw New ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.")
'Set the width & height of the image
_width = width
_height = height
End Sub
''' <summary>
''' Procedure to set the font to be used on the CAPTCHA image
''' </summary>
''' <param name="fontName">Name of the font (Verdana, Arial, Tahoma, etc)</param>
''' <remarks></remarks>
Private Sub SetFont(Optional ByVal fontName As String = "")
Dim font As Font
Try
‘If the user specified a font then use it
If Not String.IsNullOrEmpty(fontName) Then
font = New Font(fontName, 12.0F)
fontName = fontName
Else
‘Otherwise default to Verdana
font = New Font("Verdana", 12.0F)
fontName = fontName
End If
font.Dispose()
Catch ex As Exception
‘This ensures that if a font is specified that isnt on the end users
‘computer than a system font will be used
fontName = System.Drawing.FontFamily.GenericSerif.Name
End Try
End Sub

Next we need a random string to display on the CAPTCHA. If you look at the CAPTCHA’s being used on the Internet today there isn’t a set size of this string, so I decided to give the option of specifying how long you want your string to be. This gives the developer a little bit of flexibility when using this component. To generate the random string I used:

The only thing we have left to do is generate the CAPTCHA image. This is the large function in all of this, as it has to do a lot of work. To generate the image we start with a 32-bit bitmap, then we create a graphics object. From here we fill in the background of the graphics object (using the hatch style and 2 colors the developer specifies). From there we get the font ready, we then adjust the font (done in a loop) until it fits in the image properly. Then we warp the text randomly, add some random noise (making it even harder for a bot to read it), then finally we clean everything up. Since this image is created at runtime, there’s no image saved anywhere, no way for a “bot” to retrieve the image and try to process it. Here is the final function in this component.

That is how to create a CAPTCHA in VB.Net. At first working with the System.Drawing Namespace was very scary for me, but after creating this CAPTCHA it’s not as bad as it seems. This tutorial should also give you a very good dive into working with the System.Drawing Namespace, what it can do, how to do certain things. If, after playing with this code, you are having a hard time understanding how to make it work on your site feel free to either send me a private message, or better yet post a comment here and I will be more than happy to post an example of it in action, to help you along.

Since I have this code under a GNU General Public License, meaning you can alter and modify it how you see fit I am also uploading both the DLL file and the source code, all I ask is that you keep my header in tact. I have no problems with anyone using this commercially, but if you do it would be nice if there was a mention of me somewhere, if not, that’s okay too. I just hope this tutorial helps at least one person, if I can help one person at a time then I am giving back to the community that has helped me get to where I am today.

hye...
i need to put the captcha graphic in my web registration form.
but i dunno how... is it all the codes put in one page..
can u give me the step by step from beginning how i should put in my form.thanks

hey fantastic idea! how do i implement the image into a form, ive tried my saving the image created to a variable called myBMP but there is no way i can set the system.drawing.image part of a webcontrol image. could you help with this?

Hey, i downloaded this captcha solution and it works fine, thats if you want to mess around adding in the idea of changing the text everytime a request is made for a captcha image, i have created a function inside the captcha class called "GenerateRandomString" which generates a random string so you dont have to worry about that side of it, i will submit this back to dream in code once it is completed with an explaination of how to implement this into your websites.....