rain
2024-05-16 6ad595014ddd8578ead23116b3f9cb00f828627a
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
package com.dji.sample.territory.utils;
 
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.util.encoders.Hex;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
 
public class HashUtil {
    public static String SM3Hash(File file) {
        String filePath = String.valueOf(file);
        String hashHex = "";
        try {
            byte[] fileBytes = readFile(filePath);
            byte[] hash = calculateHash(fileBytes);
             hashHex = Hex.toHexString(hash);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return hashHex;
    }
 
    private static byte[] readFile(String filePath) throws IOException {
        FileInputStream fis = new FileInputStream(filePath);
        byte[] buffer = new byte[1024];
        int bytesRead;
        StringBuilder sb = new StringBuilder();
        while ((bytesRead = fis.read(buffer)) != -1) {
            sb.append(new String(buffer, 0, bytesRead));
        }
        fis.close();
        return sb.toString().getBytes();
    }
 
    private static byte[] calculateHash(byte[] input) {
        SM3Digest digest = new SM3Digest();
        digest.update(input, 0, input.length);
        byte[] hash = new byte[digest.getDigestSize()];
        digest.doFinal(hash, 0);
        return hash;
    }
}