如何獲取Java中任何給定文件的MD5校驗和? 如何使用 Apache Common 的 DigestUtils.md5Hex 實用程序?
已發表: 2021-08-28
加強企業應用程序的安全性是任何組織面臨的最大挑戰。
考慮這個實際的生產場景:
- 您有一個從文件中
reads the value
的應用程序 - 根據文件值,它
performs some operations
,如添加/刪除/執行 - 您已在生產環境中部署此應用程序
- 如果某些
unauthorized person
在您不知情的情況下changes the value
怎麼辦? - 您的應用程序
simply gets new value
並運行可能導致unexpected outcome
的邏輯 - 如果您可能為該文件啟用了 MD5 校驗和 - 您
could have created an exception
,並且you could have prevented disaster
或意外結果
什麼是 MD5 校驗和?
文件的 MD5 校驗和是128-bit value
,類似於文件的指紋。 它可用於比較文件及其完整性控制。
為不同的文件獲得相同的值幾乎是不可能的。 在本教程中,我們將創建簡單的 Java 程序,該程序為給定文件創建並返回 MD5 值。 在我們的例子中,它是index.php
文件。
讓我們開始吧:
第1步
創建公共類CrunchifyGetMD5ForFile.java
第2步
將以下兩個 maven 依賴項導入項目的pom.xml
文件。 將項目轉換為 Maven 項目的教程。
1 2 3 4 5 6 7 8 9 10 |
< dependency > < groupId > commons - codec < / groupId > < artifactId > commons - codec < / artifactId > < version > 1.10 < / version > < / dependency > < dependency > < groupId > commons - io < / groupId > < artifactId > commons - io < / artifactId > < version > 2.4 < / version > < / dependency > |
我們正在使用commons-codec
和commons-io
庫。
第三步
使用DigestUtils.md5Hex
實用程序創建 MD5 校驗和並在控制台上打印結果。
DigestUtils.md5Hex => encodeHex 實現
1 2 3 4 5 6 7 8 9 10 |
protected static char [ ] encodeHex ( final byte [ ] data , final char [ ] toDigits ) { final int l = data . length ; final char [ ] out = new char [ l < < 1 ] ; // two characters form the hex value. for ( int i = 0 , j = 0 ; i < l ; i ++ ) { out [ j ++ ] = toDigits [ ( 0xF0 & data[i]) >>> 4]; out [ j ++ ] = toDigits [ 0x0F & data[i]]; } return out ; } |
這是一個完整的程序。
創建類 crunchifyGetMd5ForFile.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
package crunchify . com . tutorials ; import org . apache . commons . codec . digest . DigestUtils ; import org . apache . commons . io . IOUtils ; import java . io . File ; import java . io . FileInputStream ; import java . io . IOException ; /** * @author Crunchify.com * How to get MD5 checksum for any given file in Java? Use commons-codec's DigestUtils.md5Hex. */ public class CrunchifyGetMD5ForFile { public static String crunchifyGetMd5ForFile ( String crunchifyFile ) { // File(): Creates a new File instance by converting the given pathname string into an abstract pathname. // If the given string is the empty string, then the result is the empty abstract pathname. File myFile = new File ( crunchifyFile ) ; return crunchifyGetMd5ForFile ( myFile ) ; } public static String crunchifyGetMd5ForFile ( File crunchifyFile ) { String crunchifyValue = null ; // FileInputStream: A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. // FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. FileInputStream crunchifyInputStream = null ; try { crunchifyInputStream = new FileInputStream ( crunchifyFile ) ; // md5Hex converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order. // The returned array will be double the length of the passed array, as it takes two characters to represent any given byte. // DigestUtils(): Operations to simplify common MessageDigest tasks. This class is immutable and thread-safe. // However the MessageDigest instances it creates generally won't be. // The MessageDigestAlgorithms class provides constants for standard digest algorithms that can be // used with the getDigest(String) method and other methods that require the Digest algorithm name. // toByteArray(): Get the contents of an InputStream as a byte[]. // This method buffers the input internally, so there is no need to use a BufferedInputStream. crunchifyValue = DigestUtils . md5Hex ( IOUtils . toByteArray ( crunchifyInputStream ) ) ; // md5Hex(): Calculates the MD5 digest and returns the value as a 32 character hex string. } catch ( IOException e ) { log ( "Hey there is an error: " + e ) ; } finally { // closeQuietly(): Unconditionally close an InputStream. // Equivalent to InputStream.close(), except any exceptions will be ignored. // This is typically used in finally blocks. IOUtils . closeQuietly ( crunchifyInputStream ) ; } return crunchifyValue ; } // Simple log util private static void log ( String string ) { System . out . println ( string ) ; } public static void main ( String [ ] agrs ) { // Let's get MD5 for File index.php located at /Users/app/Download/ String file = "//cdn.crunchify.com/Users/app/Download/crunchify.png" ; String md5Value = crunchifyGetMd5ForFile ( file ) ; log ( "File: " + file + " \nValue: " + md5Value ) ; } } |
只需將上述程序作為 Java 應用程序運行,您將看到與此類似的結果。

IntelliJ IDEA 控制台結果:
1 2 3 4 |
File : / Users / app / Download / crunchify . png Value : 103e7ae51e641d674780f7a03b491321 Process finished with exit code 0 |
您將如何在運行時使用此 MD5 校驗和來驗證文件完整性?
您可以在運行時將此 MD5 校驗和與存儲在您的數據庫(如 MySQL、Oracle 等)中的值進行比較。
還有許多其他方法可以實現相同的目標,但我們將在以後的教程中討論這一點。