这是一个非常好用的使用MD5+salt加密的工具类。使用这个工具类,非常简单
从前台拿到密码password,直接HexUtil.getEncryptedPwd(password)就可以返回一个长度为56的字符串,可以用来保存到数据库中,相反,登录的时候,因为MD5加密是不可逆的运算,只能拿用户输入的密码走一遍MD5+salt加密之后,跟数据库中的password比较,看是否一致,一致时密码相同,登录成功,通过调用HexUtil.validpassword(String password,String dbpassword)方法,就可以了,不用再做其他事。
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
public class MD5Utils {
private final static String HEX_NUMS_STR = "0123456789ABCDEF";
private final static Integer SALT_LENGTH = 12;
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] hexChars = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4 | HEX_NUMS_STR
.indexOf(hexChars[pos + 1]));
}
return result;
}
public static String byteToHexString(byte[] salt){
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < salt.length; i++) {
String hex = Integer.toHexString(salt[i] & 0xFF);
if(hex.length() == 1){
hex = '0' + hex;
}
hexString.append(hex.toUpperCase());
}
return hexString.toString();
}
public static boolean validpassword(String password, String dbpassword)
throws NoSuchAlgorithmException, UnsupportedEncodingException{
byte[] pwIndb = hexStringToByte(dbpassword);
byte[] salt = new byte[SALT_LENGTH];
System.arraycopy(pwIndb, 0, salt, 0, SALT_LENGTH);
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(salt);
md.update(password.getBytes("UTF-8"));
byte[] digest = md.digest();
byte[] digestIndb = new byte[pwIndb.length - SALT_LENGTH];
System.arraycopy(pwIndb, SALT_LENGTH, digestIndb, 0,digestIndb.length);
if(Arrays.equals(digest, digestIndb)){
return true;
}else{
return false;
}
}
public static String getEncryptedPwd(String password)
throws NoSuchAlgorithmException, UnsupportedEncodingException{
byte[] pwd = null;
SecureRandom sc= new SecureRandom();
byte[] salt = new byte[SALT_LENGTH];
sc.nextBytes(salt);
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(salt);
md.update(password.getBytes("UTF-8"));
byte[] digest = md.digest();
pwd = new byte[salt.length + digest.length];
System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH);
System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length);
return byteToHexString(pwd);
}
}