import org.apache.commons.codec.binary.Hex;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
public class PwdUtil {
/**
* 生成密码盐
*
* @return 密码盐
*/
public static String createSalt() {
return UUID.randomUUID().toString();
}
/**
* 密码加salt加密
*
* @param pwd 密文密码
* @param salt 密码盐
* @return 加盐密码
*/
public static String process(String pwd, String salt) {
return md5(sha256(pwd, salt));//将密码加盐之后 通过MD5降位
}
private static String sha256(String pwd, String salt) {
try {
MessageDigest msgDigest = MessageDigest.getInstance("SHA-256");
if (salt != null && salt.length() > 0) {
msgDigest.update(salt.getBytes());
}
byte[] digest = msgDigest.digest(pwd.getBytes());
return new String(new Hex().encode(digest));
} catch (NoSuchAlgorithmException e) {
return null;
}
}
private static String md5(String value) {
if (value == null)
return null;
try {
MessageDigest messagedigest = MessageDigest.getInstance("MD5");
messagedigest.update(value.getBytes());
byte[] digest = messagedigest.digest();
return toHex(digest);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
private static String toHex(byte abyte0[]) {
StringBuffer stringbuffer = new StringBuffer();
for (int i = 0; i < abyte0.length; i++) {
String s = Integer.toHexString(abyte0[i] & 0xff);
if (s.length() < 2) {
stringbuffer.append("0");
}
stringbuffer.append(s);
}
return stringbuffer.toString();
}
} 这个密码工具类那些地方可以优化