java code to get the MD5 of the file

content

 

What is MD5 of a file?

Several ways for java code to get MD5

method one:

Method Two:

Method three:

Method four:

Method five:

Summarize

What is MD5 of a file?

MD5 is the text bai signature, equivalent to our identity du The certificate is unique.

MD5 On forums, software releases zhi frequently used to ensure dao The correctness of the file, to prevent some people from stealing the program, adding some Trojan horses or tampering with the copyright, a set of verification system designed.

Every file can be used MD5 The validator calculates a fixed MD5 code. A software author often calculates in advance the value of his program's MD5 code and post it online.

Therefore, when I see a program download on the Internet, it is noted that MD5 When you code, you can write it down and use it after downloading the program MD5 The verification program calculates the MD5 code, and you note down before MD5 code comparison.

If the two are the same, then what you have downloaded is the original version. If the calculated one does not match what is indicated on the Internet, then the file you downloaded is incomplete, or someone else has manipulated it.

Several ways for java code to get MD5

The four methods of obtaining the MD5 value of a file in JAVA are actually very similar, because the core is implemented through the MessageDigest class that comes with JAVA. Obtaining the MD5 value of a file is mainly divided into three steps. The first step is to obtain the byte information of the file, the second step is to perform MD5 encryption through the MessageDigest class, and the third step is to convert it into a hexadecimal MD5 code value.

method one:

A more primitive implementation method, first read the file into memory at one time, then encrypt it with MD5 through MessageDigest, and finally manually convert it to a hexadecimal MD5 value.

private final static String[] strHex = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    public static String getMD5One(String path) {
        StringBuffer sb = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] b = md.digest(FileUtils.readFileToByteArray(new File(path)));
            for (int i = 0; i < b.length; i++) {
                int d = b[i];
                if (d < 0) {
                    d += 256;
                }
                int d1 = d / 16;
                int d2 = d % 16;
                sb.append(strHex[d1] + strHex[d2]);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

Method Two:

The difference between method 2 and method 1 is mainly in step 3. Here, the method of Integer class is used to realize hexadecimal conversion, which is more concise than method 1.

public static String getMD5Two(String path) {
        StringBuffer sb = new StringBuffer("");
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(FileUtils.readFileToByteArray(new File(path)));
            byte b[] = md.digest();
            int d;
            for (int i = 0; i < b.length; i++) {
                d = b[i];
                if (d < 0) {
                    d = b[i] & 0xff;
                    // Same as the previous line
                    // i += 256;
                }
                if (d < 16)
                    sb.append("0");
                sb.append(Integer.toHexString(d));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

Method three:

Compared with the previous two methods, method 3 is a little different in reading file information. Here, a file is read in multiple times. For large files, this method is recommended, which takes up less memory. The third step is to perform hexadecimal conversion through the method provided by the BigInteger class, which is similar to the second method.

public static String getMD5Three(String path) {
        BigInteger bi = null;
        try {
            byte[] buffer = new byte[8192];
            int len = 0;
            MessageDigest md = MessageDigest.getInstance("MD5");
            File f = new File(path);
            FileInputStream fis = new FileInputStream(f);
            while ((len = fis.read(buffer)) != -1) {
                md.update(buffer, 0, len);
            }
            fis.close();
            byte[] b = md.digest();
            bi = new BigInteger(1, b);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bi.toString(16);
    }

 

Method four:

If you only need to use the standard MD5, in fact, one line of code is enough. The commons-codec package that comes with JAVA provides a method to obtain the hexadecimal MD5 value. In terms of the underlying implementation, a file is read in multiple times, similar to method three. So the performance is also good

 DigestUtils.md5Hex(new FileInputStream(path));

 

Method five:

The parameters received by method 5 are directly in the form of MultipartFile, which can be directly and practically used in the process of uploading some files, saving the operation of the file stream.

  /**
     * Get the md5 of the uploaded file
     *
     * @param file Upload file MD5
     * @return
     */
    public static String getFileMd5(MultipartFile file)  {
        try {
            byte[] uploadBytes = file.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] digest = md5.digest(uploadBytes);
            String hashString = new BigInteger(1, digest).toString(16);
            return hashString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

Summarize

Either method is possible, depending on actual needs.

Tags: Java

Posted by Entanio on Tue, 10 May 2022 19:09:02 +0300