A Password oneway encryption utility  

Posted by Kishore in

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.w3c.tools.codec.Base64FormatException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class PasswordUtil {
private static PasswordUtil instance = null;

public static PasswordUtil getInstance() {
if (instance == null) {
instance = new PasswordUtil();
}

return instance;
}

public synchronized String encrypt(String password) {
MessageDigest messageDigest = null;

try {
messageDigest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}

try {
messageDigest.update(password.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}

byte raw[] = messageDigest.digest();
String hash = (new BASE64Encoder()).encode(raw);
return hash;
}

public boolean verifyPassword(String passwordBytes, String passwordHash)
throws NoSuchAlgorithmException {
return encrypt(passwordBytes).equals(passwordHash);
}

}

This entry was posted on Aug 27, 2008 at Wednesday, August 27, 2008 and is filed under . You can follow any responses to this entry through the comments feed .

0 comments

Post a Comment