Archive | Programming RSS feed for this section

Easy MD5 Encryption In JSP

9 Sep

As a few of you may know, it is pretty easy to encrypt plain text using MD5. It can be acheived just by calling the function md5(“plaintext”).

But when I recently started working on a Java-based web application, I realised that its not as easy to do it in JSP. So after a bit of research and looking around, I found a cool, simple solution to this problem. Here is the sample code which you can use in your JSP file or a Bean to do the encryption. (You need to import java.security.MessageDigest for this to work.)

String plainText = “root”;
MessageDigest md = MessageDigest.getInstance(“MD5″);
md.update(plainText.getBytes());

byte[] digest = md.digest();
StringBuffer hexString = new StringBuffer();

for (int i = 0; i < digest.length; i++) {
plainText = Integer.toHexString(0xFF & digest[i]);

if (plainText.length() < 2) {
plainText = “0″ + plainText;
}

hexString.append(plainText);
}

out.print(hexString.toString());

This can be a very effective way to encrypt passwords (after accepting them with the FORM POST method) before storing them in the database. Hope this little script will help at least a few.