| | |
| | | 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); |
| | | return sm3(fileBytes); |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | return hashHex; |
| | | return ""; |
| | | } |
| | | |
| | | private static byte[] readFile(String filePath) throws IOException { |
| | | public static byte[] readFile(String filePath) throws IOException { |
| | | FileInputStream fis = new FileInputStream(filePath); |
| | | byte[] buffer = new byte[1024]; |
| | | int 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; |
| | | public static String sm3(byte[] data) { |
| | | byte[] md = new byte[32]; |
| | | SM3Digest sm3 = new SM3Digest(); |
| | | sm3.update(data, 0, data.length); |
| | | sm3.doFinal(md, 0); |
| | | String s = new String(Hex.encode(md)); |
| | | return s.toUpperCase(); |
| | | } |
| | | public static void main(String[] args) { |
| | | System.out.println(SM3Hash(new File("src/main/resources/FJ_11.jpeg"))); |
| | | } |
| | | } |