直接上代码了,都有备注
private final static String[] strDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
"e", "f"};
public static void main(String[] args) {
String password = getPassword();
System.out.println("加密的密码:"+password);
}
public static String getPassword() {
int len = 16;
int f = 0;
char[] pwd = new char[len];
for (int i = 0; i < len; i++) {
//随机生成0,1,2三个数中的一个f,作为判断条件
f = (int) (Math.random() * 3);
//System.out.println(f);
if (f == 0) {
//生成0-9之间的随机数字
pwd[i] = (char) ('0' + Math.random() * 10);
} else if (f == 1) {
//随机生成一个小写字母
pwd[i] = (char) ('a' + Math.random() * 26);
} else {
//随机生成一个大写字母
pwd[i] = (char) ('A' + Math.random() * 26);
}
}
String str = new String(pwd);
String md5Code = getMD5Code(str);
return md5Code;
}
/**
* 将给定的字符串经过md5加密后返回
*
* @param str
* @return
*/
public static String getMD5Code(String str) {
String resultString = null;
try {
// 将给定字符串追加一个静态字符串,以提高复杂度
System.out.println("未加密的密码:"+str);
resultString = new String(str);
MessageDigest md = MessageDigest.getInstance("MD5");
// md.digest() 该函数返回值为存放哈希值结果的byte数组
resultString = byteToString(md.digest(resultString.getBytes()));
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return resultString;
}
/**
* 转换字节数组为16进制字串
*
* @param bByte
* @return
*/
private static String byteToString(byte[] bByte) {
StringBuffer sBuffer = new StringBuffer();
for (int i = 0; i < bByte.length; i++) {
sBuffer.append(byteToArrayString(bByte[i]));
}
return sBuffer.toString();
}
/**
* 返回形式为数字和字符串
*
* @param bByte
* @return
*/
private static String byteToArrayString(byte bByte) {
int iRet = bByte;
if (iRet < 0) {
iRet += 256;
}
int iD1 = iRet / 16;
int iD2 = iRet % 16;
return strDigits[iD1] + strDigits[iD2];
}
运行结果
未加密的密码:w7X0lwvsUFj86d8i
加密的密码:0a3dbada5d4edd85c83279c450030713