/* File Name: PasswordUtility.java */ package explorer.server; import java.security.SecureRandom; import java.security.MessageDigest; import java.util.Arrays; /** * PasswordUtility Class has the module to encrypt the password of the user * Using MD5 algorithm and the module to authenticate the particular User */ public class PasswordUtility { /** * used to generat a random 12byte Salt */ private static byte[] getSalt() { SecureRandom saltGen; byte[] salt = new byte[12]; saltGen = new SecureRandom(); saltGen.nextBytes(salt); return salt; } /** * Encrypts the password with a random salt */ public static byte[] encrypt(String strPWD) { return encrypt(strPWD,getSalt()); } /** * Digests back the salt with tha password to check the pwd */ public static byte[] encrypt(String strPWD, byte[] salt) { MessageDigest msgDigest; byte[] encPwd = new byte[0]; byte[] SaltPwd; try { msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(salt); msgDigest.update(strPWD.getBytes()); encPwd = msgDigest.digest(); } catch(Exception e) { e.printStackTrace(); } SaltPwd = new byte[salt.length+encPwd.length]; System.arraycopy(salt,0,SaltPwd,0,salt.length); System.arraycopy(encPwd,0,SaltPwd,salt.length,encPwd.length); return SaltPwd; } /** * Authenticates the User */ public static boolean authenticate(String newPwd, byte[] SaltPwd) { byte[] salt = new byte[12]; byte[] checkPwd; System.arraycopy(SaltPwd,0,salt,0,12); checkPwd = encrypt(newPwd, salt); return Arrays.equals(SaltPwd,checkPwd); } }