MD5算法是一种非常优秀的加密算法。
MD5加密算法特点:灵活性、不可恢复性。
介绍MD5加密算法基本情况MD5的全称是Message-Digest Algorithm 5,在90年代初由MIT的计算机科学实验室和RSA Data Security Inc发明,经MD2、MD3和MD4发展而来。
Message-Digest泛指字节串(Message)的Hash变换,就是把一个任意长度的字节串变换成一定长的大整数。请注意我使用了"字节串"而不是"字符串"这个词,是因为这种变换只与字节的值有关,与字符集或编码方式无关。
MD5将任意长度的"字节串"变换成一个128bit的大整数,并且它是一个不可逆的字符串变换算法,换句话说就是,即使你看到源程序和算法描述,也无法将一个MD5的值变换回原始的字符串,从数学原理上说,是因为原始的字符串有无穷多个,这有点象不存在反函数的数学函数。
MD5的典型应用是对一段Message(字节串)产生fingerprint(指纹),以防止被"篡改"。举个例子,你将一段话写在一个叫readme.txt文件中,并对这个readme.txt产生一个MD5的值并记录在案,然后你可以传播这个文件给别人,别人如果修改了文件中的任何内容,你对这个文件重新计算MD5时就会发现。如果再有一个第三方的认证机构,用MD5还可以防止文件作者的"抵赖",这就是所谓的数字签名应用。
MD5还广泛用于加密和解密技术上,在很多操作系统中,用户的密码是以MD5值(或类似的其它算法)的方式保存的,用户Login的时候,系统是把用户输入的密码计算成MD5值,然后再去和系统中保存的MD5值进行比较,而系统并不"知道"用户的密码是什么。
一些黑客破获这种密码的方法是一种被称为"跑字典"的方法。有两种方法得到字典,一种是日常搜集的用做密码的字符串表,另一种是用排列组合方法生成的,先用MD5程序计算出这些字典项的MD5值,然后再用目标的MD5值在这个字典中检索。
即使假设密码的最大长度为8,同时密码只能是字母和数字,共26+26+10=62个字符,排列组合出的字典的项数则是P(62,1)+P(62,2)....+P(62,8),那也已经是一个很天文的数字了,存储这个字典就需要TB级的磁盘组,而且这种方法还有一个前提,就是能获得目标账户的密码MD5值的情况下才可以。
在很多电子商务和社区应用中,管理用户的Account是一种最常用的基本功能,尽管很多Application Server提供了这些基本组件,但很多应用开发者为了管理的更大的灵活性还是喜欢采用关系数据库来管理用户,懒惰的做法是用户的密码往往使用明文或简单的变换后直接保存在数据库中,因此这些用户的密码对软件开发者或系统管理员来说可以说毫无保密可言,本文的目的是介绍MD5的Java Bean的实现,同时给出用MD5来处理用户的Account密码的例子,这种方法使得管理员和程序设计者都无法看到用户的密码,尽管他们可以初始化它们。但重要的一点是对于用户密码设置习惯的保护。
Java实现MD5:
/**
* MD5算法 2007年12月27日 Encrypt.java 32位
*/
package org.ace.test;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
*
* @author Ace
* @version 1.00
*/
public class Encrypt {
/**
* 将一个字符串使用MD5加密并返回.
*
* @param value
* 待加密的字符串.
* @return 返回使用MD5算法加密的字节串序列.
*/
public final String getMD5Message(String value) {
// 定义十六进制序列.
String hexSequence = "0123456789abcdef";
// 将待转换的字符串分解为字节串.
byte[] prepareMessage = value.getBytes();
// 生成实现MD5摘要算法的 MessageDigest 对象.
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 使用指定的字节串更新此摘要.
md.update(prepareMessage);
// 完成哈希计算.
byte[] newMessage = md.digest();
// 获得新字节串的长度.
int length = newMessage.length;
// 定义最终返回的字节串.
char[] message = new char[length * 2];
// 定义为最终字节串赋值的索引.
int index = 0;
// 循环遍历新字节串的每一位,变换后追加至最终字节串.
for (int i = 0; i < length; i++) {
message[index++] = hexSequence.charAt(newMessage[i] >>> 4 & 0xf);
message[index++] = hexSequence.charAt(newMessage[i] & 0xf);
}
// 返回经过MD5加密的最终字节串.
return new String(message);
}
}
MD5加密算法,Java另外一种64位实现:
- public class Base64 {
- final static String baseTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- /**
- * Encode a byte array.
- *
- * @param bytes a byte array to be encoded.
- * @return encoded object as a String object.
- */
- public static String encode(byte[] bytes) {
- StringBuffer tmp = new StringBuffer();
- int i = 0;
- byte pos;
- for(i=0; i < (bytes.length - bytes.length%3); i+=3) {
- pos = (byte) ((bytes[i] >> 2) & 63);
- tmp.append(baseTable.charAt(pos));
- pos = (byte) (((bytes[i] & 3) << 4) + ((bytes[i+1] >> 4) & 15));
- tmp.append(baseTable.charAt( pos ));
- pos = (byte) (((bytes[i+1] & 15) << 2) + ((bytes[i+2] >> 6) & 3));
- tmp.append(baseTable.charAt(pos));
- pos = (byte) (((bytes[i+2]) & 63));
- tmp.append(baseTable.charAt(pos));
- // Add a new line for each 76 chars.
- // 76*3/4 = 57
- if(((i+2)%56) == 0) {
- tmp.append("/r/n");
- }
- }
- if(bytes.length % 3 != 0) {
- if(bytes.length % 3 == 2) {
- pos = (byte) ((bytes[i] >> 2) & 63);
- tmp.append(baseTable.charAt(pos));
- pos = (byte) (((bytes[i] & 3) << 4) + ((bytes[i+1] >> 4) & 15));
- tmp.append(baseTable.charAt( pos ));
- pos = (byte) ((bytes[i+1] & 15) << 2);
- tmp.append(baseTable.charAt(pos));
- tmp.append("=");
- } else if(bytes.length % 3 == 1) {
- pos = (byte) ((bytes[i] >> 2) & 63);
- tmp.append(baseTable.charAt(pos));
- pos = (byte) ((bytes[i] & 3) << 4);
- tmp.append(baseTable.charAt( pos ));
- tmp.append("==");
- }
- }
- return tmp.toString();
- }
- /**
- * Encode a String object.
- *
- * @param src a String object to be encoded with Base64 schema.
- * @return encoded String object.
- */
- public static String encode(String src) {
- return encode(src.getBytes());
- }
- public static byte[] decode(String src) throws Exception {
- byte[] bytes = null;
- StringBuffer buf = new StringBuffer(src);
- // First, Remove white spaces (/r/n, /t, " ");
- int i = 0;
- char c = ' ';
- char oc = ' ';
- while( i < buf.length()) {
- oc = c;
- c = buf.charAt(i);
- if( oc == '/r' && c == '/n') {
- buf.deleteCharAt(i);
- buf.deleteCharAt(i-1);
- i -= 2;
- } else if( c == '/t') {
- buf.deleteCharAt(i);
- i --;
- } else if( c == ' ') {
- i --;
- }
- i++;
- }
- // The source should consists groups with length of 4 chars.
- if(buf.length() % 4 != 0) {
- throw new Exception("Base64 decoding invalid length");
- }
- // pre-set byte array size.
- bytes = new byte[3 * (buf.length() / 4)];
- //int len = 3 * (buf.length() % 4);
- //System.out.println("Size of Bytes array: " + len);
- int index = 0;
- // Now decode each group
- for(i = 0; i < buf.length(); i+=4) {
- byte data = 0;
- int nGroup = 0;
- for(int j = 0; j < 4; j++) {
- char theChar = buf.charAt(i + j);
- if(theChar == '=') {
- data = 0;
- } else {
- data = getBaseTableIndex(theChar);
- }
- if(data == -1) {
- throw new Exception("Base64 decoding bad character");
- }
- nGroup = 64*nGroup + data;
- }
- bytes[index] = (byte) (255 & (nGroup >> 16));
- index ++;
- bytes[index] = (byte) (255 & (nGroup >> 8));
- index ++;
- bytes[index] = (byte) (255 & (nGroup));
- index ++;
- }
- byte[] newBytes = new byte[index];
- for(i = 0; i < index; i++) {
- newBytes[i] = bytes[i];
- }
- return newBytes;
- }
- /**
- * Find index number in base table for a given character.
- *
- */
- protected static byte getBaseTableIndex(char c) {
- byte index = -1;
- for(byte i = 0; i < baseTable.length(); i ++) {
- if(baseTable.charAt(i) == c) {
- index = i;
- break;
- }
- }
- return index;
- }
- public static void main(String[] args) {
- String encodedString = Base64.encode("Hello PHPRPC".getBytes());
- System.out.println(encodedString);
- }
- }