`
gogole_09
  • 浏览: 201964 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

MD5验证文件

阅读更多

 参考多篇网上的资料。  记录一下 java用MD5验证文件的方法,

 

import java.applet.*;   
import java.io.*;   
import java.security.*;   
  
/**
 * MD5比较文件
 * @author Administrator
 *
 */
public class MD5Test {   
    public static char[] hexChar = {'0', '1', '2', '3',   
                                   '4', '5', '6', '7',   
                                   '8', '9', 'a', 'b',   
                                   'c', 'd', 'e', 'f'};   
    public static void main(String[] args) throws  
            Exception {   
    	String fileName = "D:\\FinanceSetup.zip";
    	
        String fileName2 = "D:\\httpd-2.2.14.tar.gz";
        
        String hashType = "MD5";   
        System.out.println(hashType + " == " +   
        		getHash(fileName2, hashType));   
        System.out.println(hashType + " == " +   
                           getHash(fileName, hashType));   
    }   
  
    public static String getHash(String fileName, String hashType) throws  
            Exception {   
        InputStream fis;   
        fis = new FileInputStream(fileName);   
        byte[] buffer = new byte[1024];   
        MessageDigest md5 = MessageDigest.getInstance(hashType);   
        int numRead = 0;   
        while ((numRead = fis.read(buffer)) > 0) {   
            md5.update(buffer, 0, numRead);   
        }   
        fis.close();   
        return toHexString(md5.digest());   
    }   
  
    /**
     * 0xf0 :为16进制数 
     *    转成10进制为 240
     *    转成2进制为  11110000 
     * 
     *  解释:(b[i]&0xf0)>>>4  
	 *			-->将b[i]的低4位清零后, (将b[i]转成2进制  再 & 0xf0 既  & 11110000 ; 例如:01010101 & 11110000 结果是 01010000) 
	 *			再无符号的右移4位 既取出高4位 
	 *			作为数组hexChar的下标 拿到对应的16进制符
     * @param b byte数组
     * @return
     */
    public static String toHexString(byte[] b) {   
        StringBuilder sb = new StringBuilder(b.length <<1);   
        for (int i = 0; i < b.length; i++) {
            sb.append(hexChar[(b[i] & 0xf0) >>> 4]);   
            sb.append(hexChar[b[i] & 0x0f]);   
        }   
        return sb.toString();   
    }   
}  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics