Saturday, June 7, 2008

Encrypt user password before storing it to database

It is important to encrypt user password before storing it in the database. Password must be interpreted only by your java application.
Here is the sample java code to encrypt a plain password text. Before comparing password, encrypt it using following java code.

Sample Java Code

public synchronized String encrypt(String plainpassword) throws SystemUnavailableException {
MessageDigest md = null;
try
{
md = MessageDigest.getInstance("SHA");
}
catch(NoSuchAlgorithmException e)
{
throw new SystemUnavailableException(e.getMessage());
}
try
{
md.update(plainpassword.getBytes("UTF-8"));
}
catch(UnsupportedEncodingException e)
{
throw new SystemUnavailableException(e.getMessage());
}

byte data[] = md.digest();
String encryptedPassword = (new BASE64Encoder()).encode(data);
return encryptedPassword;
}

0 Java Junction comments: