Wednesday, September 19, 2012

Building your own Captcha


Capatcha is used in web forms, or forms authentication in order to apply a challenge-response to ensure that the website is dealing with human response. This means that the website is protected against brute force attack codes.
Google uses captcha in its own way (repcatcha) which could be downloaded and integrated into your code (.Net, or Php, visit: http://www.captcha.net/ for more info). Sometimes recaptcha connection doesn’t work into your site for any reason which we will not deal with it here. What are we going to talk about in this blog is that you still can write your own Captcha and use it anywhere you want. That’s what I want to share with you on my blog.
For people who will continue reading this blog, the code used is in .Net platform using C#, this doesn’t mean that you are restricted to use it only in .Net. the criteria is the same in almost all other languages.

Let’s start:
I will summarize the steps here and then enter in details.
1.      Create the web service responsible of generating the captcha image upon specific random string.
2.      Integrate the web service above in your code (through web reference and wsdl file).
3.      Write down the handler responsible of converting the byte[] (comes from web service) to a real image used in your code.
4.      Write down your code that will use the above web service and the handler.
Now let us enter into the details.



Captcha Web Service:
1.       Open a new project in visual studio, and make a new website. Add new item to the website type of web service (.asmx file) named captcha_gen.asmx, by default the code behind will be stored in the App_Code folder in a file name captcha_gen.cs, open the cs file and add the following code into it:


 [WebMethod]
    public byte[] GenCaptchaImg(string CaptchaStr)
    {
        //create Empty Img and new font
        Bitmap objBmp = new Bitmap(100, 25); //100: width, 25 height

        Graphics objGraphics = Graphics.FromImage(objBmp);
        objGraphics.SmoothingMode = SmoothingMode.AntiAlias;
        objGraphics.Clear(Color.Gray);
        objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;

        Font objFont = new Font("Verdana", 10, System.Drawing.FontStyle.Bold);

        //generate Captcha string
        string strCaptcha = string.Empty;
        strCaptcha = CaptchaStr;  //"334Aw2eQ" for example

        //Write Captcha string to the img and then generate byte[].
        objGraphics.DrawString(strCaptcha, objFont, Brushes.White, 3, 3);
        MemoryStream ms = new MemoryStream();
        objBmp.Save(ms, ImageFormat.Png);

        byte[] bmpBytes = ms.GetBuffer();
        return bmpBytes;
    }

This web method simply gets a string of characters or numbers (a random combination) and generates a byte[] array which will be later the image.
Web Service Integration
Now it’s time to build your website to use recaptcha, the following steps depend on this project. To start, open visual studio and create a new website. Then add a (Web Reference) to your website and enter the link to your web service built before. For local use enter (http://localhost/my_webservices/captcha_gen.asmx?wsdl ) this is the wsdl file of your service, then chose the web service to use, this is off course  (captcha_gen) service.
In the default.aspx.cs file in your website and at page_load event  write the following code:


 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string myStrCaptcha = StringGenerator();
            Session["just_captcha"] = myStrCaptcha;
            //define web reference and use it.
            myWebService.captcha_gen x = new myWebService.captcha_gen();
            byte[] bmpBytes = x.GenCaptchaImg(myStrCaptcha);
            HttpContext.Current.Session["ImgCaptcha"] = bmpBytes;
           
        }

    }
protected string StringGenerator()
    {
        StringBuilder builderStr = new StringBuilder();
        char ch;
        Random random = new Random((int)DateTime.Now.Ticks);
        for (int i = 0; i < 8; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builderStr.Append(ch);
        }
        return builderStr.ToString();
    }

The code above simply generate a random 8 characters string using StringGenerator() method, this method generate random 8 upper case characters and return a string of them, here you are free to build any random string generator you want. Then the code continues to call the web service (captcha_gen) which we referenced before by creating an object from it named (x), x object will call the method in the web service responsible for creating a byte[] array from the string parameter. And finally add the generated bmpBytes array to a session called ImgCaptcha to be used in the handler.
Generic Handler
In your website you are building add a generic handler to it named: ImgHandler.ashx, this handler will receive the byte[] array from the session named ImgCaptcha and then then return a png image. This handler will be referenced in an asp:image with ImageUrl=”ImgHandler.ashx” in the file default.aspx in your website. The following is the code of the handler:





 public class ImgHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState {
   
    public void ProcessRequest (HttpContext context)
    {
        //context.Response.OutputStream.Write(bmpBytes, 0, bmpBytes.Length);
        //context.Response.ContentType = "image/jpeg";
        if (context.Session["ImgCaptcha"] != null)
        {
            context.Response.ContentType = "image/png";
            byte[] image = (byte[])(context.Session["ImgCaptcha"]);
            context.Response.BinaryWrite(image);
        }
        else
        {
            context.Response.ContentType = "text/html";
            context.Response.Write("Hello World");
        }
        //context.Response.Write(HttpRuntime.Cache["img"]);
        //context.Response.BinaryWrite(imgBytes);
        //context.Response.Write("Hello World");
    }

    public bool IsReusable {
        get {
            return false;
        }
}


In this code I want to focus on an important point which some may ignore, notice how we build the class ImgHandler which inherits from IHttpHandler by default, we also add another class called IRequiresSessionState. Without this class all the sessions of the website will be null, so you have to add it in order to get the value of the session (ImgCaptcha). The hander simply read the session value and generate a response from it by writing a Binary byte[] array.

Thats all guys, if you have any questions please post me, and i will try my best to answer you.

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. I'm so glad this article helped you in someway...

    ReplyDelete
  3. wonderful!!!this is very informative creating your own captchas in ur blogspot.splendid work...keep blogging.

    Kill Captcha

    ReplyDelete