Java 文件完整性校驗 MD5 sha1 sha256 sha224 sha384 sha512


由於項目中需要使用文件做備份,並且要提供備份文件的下載功能。備份文件體積較大,為確保下載后的文件與原文件一致,需要提供文件完整性校驗。

網上有這么多此類文章,其中不少使用到了

org.apache.commons.codec.digest.DigestUtils

包中的方法,但是又自己做了大文件的拆分及獲取相應校驗碼的轉換。

DigestUtils 包已經提供了為文件流生成校驗碼的功能,可以直接調用。經測試10幾G的文件在30秒內可完成計算。

(網上提供的一些自己拆分大文件的示例,文件較小時結果正確,文件較大時結果就不太可靠了)

 

實現步驟如下:

  1. pom.xml 添加依賴
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.12</version>
    </dependency>
  2. 實現類:
    package file.integrity.check;
    
    import org.apache.commons.codec.digest.DigestUtils;
    import java.io.File;
    import java.io.FileInputStream;
    
    public class Application {
        public static void main(String[] args) throws Exception {
            File file = new File("/path/filename");
            FileInputStream fileInputStream = new FileInputStream(file);
            String hex = DigestUtils.sha512Hex(fileInputStream);
            System.out.println(hex);
        }
    }
  3.  或者:
    import org.apache.commons.codec.digest.DigestUtils;
    import static org.apache.commons.codec.digest.MessageDigestAlgorithms.SHA_512;
    import java.io.File;
    
    public class Application {
        public static void main(String[] args) throws Exception {
            File file = new File("/path/filename");
            String hex = new DigestUtils(SHA_512).digestAsHex(file);
            System.out.println(hex);
        }
    }

     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM