密码等重要信息入数据库的时候考虑数据的安全性,会将明文的密码加密,其中MD5就是其中的一种算法,在java中的MessageDigest类就是MD5的具体实现,在将转成的字节数组转成十六进制,起到加密的作用。
例子如下:
package MD5加密;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5
* @author Tms
*
*/
public class Test {
static String[] hex = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
public static void main(String[] args) throws NoSuchAlgorithmException {
String password = "tms123456";
String passwordByMD5 = encodeByMD5(password);
System.out.println("password:"+password);
System.out.println("passwordByMD5:"+passwordByMD5);
}
private static String encodeByMD5(String password) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("md5");
byte[] results = digest.digest(password.getBytes());
return byteArrayToString(results);
}
private static String byteArrayToString(byte[] results) {
StringBuffer sb = new StringBuffer();
for(int i=0;i
//per byte to string
sb.append(byteToString(results[i]));
}
return sb.toString();
}
//per byte to String (Algorithms)
private static Object byteToString(byte b) {
int n = b;
if(n<0) {
n = 256+n;
}
int d1 = n/16;
int d2 = n%16;
return hex[d1]+hex[d2];
}
}
运行结果:
password:tms123456
passwordByMD5:B76CDA5AEBD39488E8F15CE1599BEC83