java 實現CRC32和MD5

1. CRC校驗

CRC校驗實用程序庫 在數據存儲和數據通訊領域,爲了保證數據的正確,就不得不採用檢錯的手段。在諸多檢錯手段中,CRC是最著名的一種。CRC的全稱是循環冗餘校驗。
其特點是:檢錯能力極強,開銷小,易於用編碼器及檢測電路實現。從其檢錯能力來看,它所不能發現的錯誤的機率僅爲0.0047%以下。從性能上和開銷上考慮,均遠遠優於奇偶校驗及算術和校驗等方式。因而,在數據存儲和數據通訊領域,CRC無處不在:著名的通訊協議X.25的FCS(幀檢錯序列)採用的是CRC-CCITT,ARJ、LHA等壓縮工具軟件採用的是CRC32,磁盤驅動器的讀寫採用了CRC16,通用的圖像存儲格式GIF、TIFF等也都用CRC作爲檢錯手段。
Java中已經有實現好的校驗函數,簡單使用方法。
CRC32 crc32 = new CRC32();
crc32.update("abcdfg".getBytes());
System.out.println(crc32.getValue())
對於一個大文件,可以採用流的方式讀取大文件
    public static String getCRC32(File file) {
    	CRC32 crc32 = new CRC32();  
    	//MessageDigest.get
        FileInputStream fileInputStream = null;
        try {
        fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
            	crc32.update(buffer,0, length);
            }
            return crc32.getValue()+"";
        } catch (FileNotFoundException e) {
        e.printStackTrace();
            return null;
        } catch (IOException e) {
        e.printStackTrace();
            return null;
        } finally {
            try {
                if (fileInputStream != null)
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


2. MD5

Message Digest Algorithm MD5(中文名爲消息摘要算法第五版)爲計算機安全領域廣泛使用的一種散列函數,用以提供消息的完整性保護。
Java也提供了一個函數來處理MD5。使用的是 java.security.MessageDigest 類。


MessageDigest 提供了消息摘要算法,如 MD5 或 SHA,的功能。消息摘要是安全單向散列函數,它採用任意大小的數據並輸出一個固定長度的散列值。MessageDigest 對象在啓動時被初始化。使用 update 方法處理數據。在任何地方都可調用 reset 復位摘要。一旦所有需要修改的數據都被修改了,將調用一個 digest 方法完成散列碼的計算。對於給定次數的修改,只能調用 digest 方法一次。在調用 digest 之後,MessageDigest 對象被複位爲初始化的狀態。
    public static String getMD5(File file) {
        FileInputStream fileInputStream = null;
        try {
        	  MessageDigest MD5 = MessageDigest.getInstance("MD5");
        	
        fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
            MD5.update(buffer, 0, length);
            }


            return new String(Hex.encodeHex(MD5.digest()));
        } catch (FileNotFoundException e) {
        e.printStackTrace();
            return null;
        } catch (IOException e) {
        e.printStackTrace();
            return null;
        } catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
            try {
                if (fileInputStream != null)
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
		return null;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章