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
입니다. 파일과 무결성 제어를 비교하는 데 모두 유용할 수 있습니다.
다른 파일에 대해 동일한 값을 얻는 것은 거의 불가능합니다. 이 튜토리얼에서는 주어진 파일에 대한 MD5 값을 생성하고 반환하는 간단한 자바 프로그램을 만들 것입니다. 우리의 경우 index.php
파일입니다.
시작하자:
1 단계
공개 클래스 CrunchifyGetMD5ForFile.java
만들기
2 단계
프로젝트의 pom.xml
파일에 아래 두 개의 maven 종속성을 가져옵니다. 프로젝트를 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
라이브러리를 사용하고 있습니다.
3단계
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 등과 같은 y0ur 데이터베이스에 저장된 값과 비교할 수 있습니다.
동일한 결과를 얻을 수 있는 다른 방법이 많이 있지만 이에 대해서는 향후 자습서에서 논의할 것입니다.