Wednesday, March 03, 2010

Working with passwords in Java

Just about any web application you write today needs some kind of authentication mechanism. As a developer, I’d really rather just outsource the authentication process to a third party through something like OpenId. This helps me get away with not having to deal with storing and managing user credentials.

Unfortunately, this is not always possible. Sometimes, your application just has to manage it’s own credentials. When you need to do this, remember that storing passwords in plain-text in your database is always a very, very bad idea.

It’s fairly easy to implement a salted hash mechanism for protecting passwords in Java. I have a User class that holds all my user details, including credentials. In the setPassword method of this class, I do all the hashing work:

private String RNG_ALGORITHM = "SHA1PRNG";
private String DIGEST_ALGORITHM = "SHA-256";
private String DEFAULT_ENCODING = "UTF-8";

SecureRandom random = SecureRandom.getInstance(RNG_ALGORITHM);

// Generate a salt
byte[] salt = new byte[8];

MessageDigest digest = MessageDigest.getInstance(DIGEST_ALGORITHM);
byte[] hashedPassword = digest.digest(password.getBytes(DEFAULT_ENCODING));

this.password = toBase64(hashedPassword);
this.salt = fromBase64(salt);

One thing I noticed while writing this code was that Java doesn’t have any built-in ability to do base-64 conversions. So I used the Apache Commons Codec library instead.

And that’s it! The User object now contains the password in hashed form, and also holds the generated salt value. You just need to persist this to your database now.

To make it easy to verify user passwords, I also added a verifyPassword method to the User class which looks like this:

public boolean verifyPassword(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException
    if (this.salt == null || this.salt == "")
        return false;
    byte[] saltBytes = base64ToByte(this.salt);
    byte[] passwordBytes = password.getBytes(DEFAULT_ENCODING);

    MessageDigest digest = MessageDigest.getInstance(DIGEST_ALGORITHM);
    byte[] hashedPassword = digest.digest(passwordBytes);
    String newDigest = toBase64(hashedPassword);
    return (this.password.equals(newDigest));

This basically recreates a hash based on the supplied password and the stored salt and compares it with the hash that is stored in the database.

Sunday, February 28, 2010

Configuring SSL on Apache in Windows 7 (x64)

I just installed the 64-bit edition of Windows 7 on my machine at home. I use Apache to host some SVN repositories on this system. While trying to configure Apache to use SSL, I ran in to a really strange issue. After configuring the certificates and updating the configuration files, Apache refused to start with the following error:

SSLSessionCache: Invalid argument: size has to be >= 8192 bytes

The SSLSessionCache configuration directive accepts the cache size within parentheses. On x64 Windows installations, 32-bit apps go into a folder called “Program Files (x86)”. Because of this, my session cache configuration looked like this:

SSLSessionCache        "shmcb:C:/Program Files (x86)/Apache Software Foundation/Apache2.2/logs/ssl_scache(512000)"

I figured I might have to re-install, but a quick web search took me to this blog. I quickly created a soft link with

mklink –d apache c:\program files (x86)\Apache Software Foundation\Apache2.2

Now everything works fine!

Wednesday, November 18, 2009

Customize Recaptcha user interface

We have added recaptcha control on our web site to protect the website from spam hits particularly where user is asked to submit a form to get access to some information.

Check out Protect your web site from Spam for more details about re-captcha.

When we started implementing recaptcha, we could manage to integrate it very easily but some how the default recaptcha look and feel was not going with our website theme, so we decided to customize the recaptcha look and feel.

I will talk about simple steps we have followed to customize recaptcha look and feel.

Default look and feel is like :


Recaptcha control consists of following attributes :

  • recaptcha image (Empty div , <div id=”recaptcha_image”></div>)
  • Response fields (Text field with ID, recaptcha_response_field)
  • Reload button
  • Help button
    We need to take care of these attributes while defining custom theme.
    By default, recaptcha control will provide the look and feel for the recaptcha.
    To have custom look and feel, recaptcha control need to be informed that it should not create the default look and feel and just rely on the style information present on html elements with the IDs mentioned above.
    Here are the steps on how to customize:
    1) Add following javascript on your page where you want to display recaptcha

    <script type="text/javascript">
    var RecaptchaOptions = {
    theme: 'custom',
    lang: 'en',
    custom_theme_widget: 'recaptcha_widget'

    2) Add following code segment to display customized recaptcha

    <div id="recaptcha_widget" style="display:none">
    <div id="recaptcha_image"></div>
    <span class="recaptcha_only_if_image">Enter the words shown above:</span>
    <input type="text" id="recaptcha_response_field" name="recaptcha_response_field" />
    <a href="javascript:Recaptcha.reload()" style="text-decoration:none;color:Black">
    <img src="path to refresh symbol image" alt="Change" style="border:0"/></a>&nbsp;
    <a href="javascript:Recaptcha.showhelp()" style="text-decoration:none;color:Black" >
    <img src="path to help image" alt="Help" style="border:0"/></a>
    <script type="text/javascript" src="<Recaptcha public key>" >

3) CSS classes to control the state of recaptcha : Recaptcha exists in multiple states and each state is represented by different CSS class.

Recaptcha control make individual CSS class visible based on the current recaptcha state.

recaptcha_only_if_image : State when and where recaptcha image is displayed

recaptcha_only_if_incorrect_sol : State when user response was is incorrect.

recaptcha_only_if_no_incorrect_sol : State when user response is correct.

Customized interface will be like :


For more information, visit

Monday, November 09, 2009

75% of engineering students are unemployable

A Nasscom study released last week indicates that up to 75% of engineering students in India are unemployable because they lack hands-on skills. The article goes on to state that companies reject nearly 90% of college graduates because they are unfit even to be trained. Alarming as it may be, I’ve found this to be generally true for many years.

College education in India is woefully inadequate when it comes to preparing students to enter the job market. This is especially true for software engineering jobs. Most educational institutions are thoroughly short-sighted when it comes to imparting skills that are useful in the real world. Fundamental concepts like functional programming, object orientation and algorithms are given just a cursory glance. Students fail to appreciate the depth of these subjects and are armed with nothing more than a basic understanding of how to develop “Hello, World!” in a handful of languages. I honestly doubt if there is a programming course running anywhere in the country that forces students to write programs with more than 200 lines of code in them. If any do exist, they are a precious exception, not the norm.

Needless to say, in the real world we don’t deal with programs as trivial as “Hello, World!”. Therein lies the disconnect. Hundreds of thousands of engineers are graduating every year from institutes across the country. Their utter lack of preparedness for facing real-world challenges in the IT industry surprises both the students and their employers alike.

This is the reason why the larger IT services companies like TCS and Infosys spend massive amounts of time and money in developing learning centres and training programs to help bring these newcomers up to speed on what’s required of them. The article indicates that Infosys has extended their training program to 29 weeks.

That’s seven months of training.

Think about that for a minute. Seven months of time, money and lost productivity spent in teaching a software engineer to, well, think like a software engineer. Startups and SMEs don’t have the luxury of investing that amount of effort into people. You’re either working at a 110% on day one, or you’re not working here at all.

If you’re an engineering student, there should be just one thing on your mind right now. The question you should all be asking yourself is this – what’s your plan to get yourself into that 25% of “employable” engineers? It’s unlikely your current institution is going to be of great help. As Einstein once stated, “Problems cannot be solved by thinking within the framework in which the problem was created.”

You’ll need to find your own ways to augment your theoretical education with practical experience. You’ll want to enroll for intensive training programs in technologies and domains that interest you. Just be sure to pick programs that take you far beyond “Hello, World!”. Nothing beats real work experience, though, so consider taking up internships every semester if time permits. You’ll discover that there’s a lot more to software development than writing code and the experience you gain will help you tremendously.

If you're interested in enhancing your skills through instructor-led training programs, TetraStorm has a range of in-depth training programs that combine technical training with hands-on labs in some really exciting areas like telecommunications and networking, web application development, Java/JEE, and graphics and web design. Our three month programs arm you with the technical skills and hands-on experience required to tackle real-world projects.

If you’ve got the time, you should also opt for the additional three month product development program where we’ll put your newly acquired skills to the test while developing an actual product. All of our programs are designed, reviewed and delivered by industry veterans who have spent decades developing best-of-breed solutions for customers around the world while working with some of India’s largest and most respected IT consultancy firms.

What are you waiting for?

Sunday, October 04, 2009

Protect your web site from Spam

We had added few download forms on our web site. These download form were supposed to capture Name and Email address of user before download starts so that we followup with them at a later stage.

Sooner we realized that its quite possible for some one to write some script and flood out web site with spurious download request by providing any name and email address.

We thought of developing some mechanism to protect the web site from such type of attacks. In this process we got to know about Re-Captcha which lets you differentiate between human initiated request machine initiated request.

After some study, we found that this will be the ideal for this type of problems. has download forms where we have
implemented re-captcha solution to avoid spam.

Download form asks user to provide Name and Email address in order to continue with the download.
Along with Name and Email Address, user is asked to enter the text displayed in re-captcha.
Download the allowed only if the re-captcha text and user entered text matches.

This will ensure that the download request has been initiated by human and not by machine.
This is how download form look like:

User is supposed to read the text displayed and enter in the text box provided, along with Name and Email address.

Download will proceed only if entered text matches with the displayed text.

If displayed text is not readable, user can request for fresh text by clicking refresh icon.

Here are some basic information about re-captcha and how to use it in your web site.

ReCaptcha provides solution to differentiate between human and machine. It provides CAPTCHA service which that tells whether user is human or machine.

Here are some simple steps to implement ReCaptcha in website:

1) Register and Login to ReCaptcha web site :
2) Create key pair for the web site where you want to implement recaptcha
a. Public and Private keys will be created for the domain you have specified. This will look like :

Add following JavaScript within your html form tag

This script will bring re-captcha on your web site. You form should now look like

4) End user need to fill in the captcha form fields along with other form fields.
5) User is asked to enter what they see on the image
6) This ensures that system don’t generate spam request. It would be very difficult for any machine or automated process to know what is going to be displayed which you have to send back.
7) Validate the form for the user input (other than other form fields.
8) Step 3 above will result in two form field:
- recaptcha_challenge_field : containing the encrypted value for the challenge text
- recaptcha_response_field : for capturing the user response
9) On form submit, along with the defined form fields, retrieve the above two field values from request in-order to validate the response entered by the user
10) On server side:
- Retrieve value for recaptcha_challenge_field
- Retrieve value for recaptcha_response_field
- Call passing following as request parameter

* privatekey=Private key generated for the domain
* remoteip=IP Address of the client machine
* challenge=Value from recaptcha_challenge_field field
* response=Value from recaptcha_response_field field

11) Response from this URL contains string “true” or “false” indicating whether user recaptcha response was correct or not.
12) Response contains multiple lines. Split the response on “\n”. Get the first line from split and search for “true” or “false” string. Control the flow as per the response

For more information, visit