MD5是一種加密、壓縮算法。在爬蟲項目中獎URL壓縮爲128位的散列值。在Java 中,java.security.MessageDigest 中已經定義了MD5 的計算,只需要簡單地調用即可得到MD5 的128 位整數。然後將此128 位(16 個字節)轉換成十六進制表示即可。
java代碼實現:
import java.math.BigInteger;
import java.security.MessageDigest;
public class MD5 {
public static String getMD5(String source) {
// TODO Auto-generated method stub
String result=null;
try{
//獲取摘要
MessageDigest md=MessageDigest.getInstance("MD5");
//更新摘要,參數爲String轉換成的byte數組
md.update(source.getBytes());
//用digest函數處理數據並返回密文結果,密文結果也是byte數組。
//用BigInteger轉爲16進制字符串,參數1表示正數,toString的參數表示轉換後的進制
result= new BigInteger(1,md.digest()).toString(16);
}catch(Exception e){
e.printStackTrace();
}
return result;
}
}
參考文獻:
自己動手寫網絡爬蟲
java MD5工具類