java
MD5
参考blog:
http://blog.163.com/yxhui_cool/blog/static/770197702012291433339/
public class MD5 {
/**
* @param password the String to be encrypted
* @return the encrypted password
* @throws NoSuchAlgorithmException
*/
public static String encrypt(String password)
throws NoSuchAlgorithmException {
MessageDigest md;
// 生成一个MD5加密计算摘要
md = MessageDigest.getInstance("MD5");
// 计算md5函数
md.update(password.getBytes());
// digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
// BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
// 基数为8时生成的字符串只有01234567 , 基数为16 时生成的字符串包含0-9 a-f 使用16进制时秘药的长度为32位
byte[] bytes = md.digest();
password = new BigInteger(1, bytes).toString(16);
return password;
}
public static void main(String[] args) throws NoSuchAlgorithmException {
System.out.println(MD5.encrypt("password"));
}
}
MD5加密在理论上是不可逆的,相同的字符串是具有相同的MD5秘钥,将加密的字符串存放到数据库,下次再使用此字符串的时候,将字符串的秘钥与数据库中的值进行比较,可以鉴别是否是同一个字符串