MD5叫信息-摘要算法,是一种密码的算法,它可以对任何文件产生一个唯一的MD5验证码,每个文件的MD5码就如同每个人的指纹一样,都是不同的.
在开发中,对于用户的密码不能使用明文存入到数据库中,中间要经过一定的算法,对密码进行转换成暗文,MD5是很好的一种选择,MD5是一种不可逆的字符串变换算法,我们在使用的时候,将用户密码转换成MD5值存入到数据库中,当用户登录是同样对密码进行运算得到MD5值,再将该值与数据库中得MD5值进行比较,若相同则登录成功,否则失败。
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
public String toMd5(String input) {
MessageDigest mDigest = null ;
String string = null ;
try {
mDigest = MessageDigest.getInstance("MD5") ;
char[] chars = input.toCharArray() ;
byte[] byteArray = new byte[chars.length] ;
for(int i = 0 ;i<chars.length ;i++){
byteArray[i] = (byte) chars[i] ;
}
byte[] bytes = mDigest.digest(byteArray) ;
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
int val = ((int) bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
string = hexValue.toString() ;
System.out.println(string); //该行输出为:a1d1b2bdd513d88384c47a5f47b04079
return string;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}finally{
return string ;
}
}
public static void main(String[] args) {
MD5 md5 = new MD5() ;
md5.toMd5("张学友") ;
}
}