Tuesday, January 27, 2009

MD5 Encryption in Java

This is useful for storing passwords in a database though still vulnerable to md5 dictionary attacks, anyway, here’s a static method.



public static String encrypt(String text) {
String ecryptedText = "";
try {
MessageDigest md5Encrypt = MessageDigest.getInstance("MD5");
md5Encrypt.update(text.getBytes(), 0, text.length());
ecryptedText = new BigInteger(1, md5Encrypt.digest()).toString(16);
} catch (NoSuchAlgorithmException exception) {
exception.printStackTrace();
}
return ecryptedText;
}

This will return the MD5-encrypted string. Have a great day!


Edit: MD5 is hashing therefore not an encryption.

No comments: