|
| 1 | +/** |
| 2 | + * Copyright (c) 2023 - present TinyEngine Authors. |
| 3 | + * Copyright (c) 2023 - present Huawei Cloud Computing Technologies Co., Ltd. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license. |
| 6 | + * |
| 7 | + * THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, |
| 8 | + * BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR |
| 9 | + * A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS. |
| 10 | + * |
| 11 | + */ |
| 12 | + |
| 13 | +package com.tinyengine.it.common.utils; |
| 14 | + |
| 15 | +import org.springframework.web.multipart.MultipartFile; |
| 16 | +import java.security.MessageDigest; |
| 17 | +import java.io.InputStream; |
| 18 | + |
| 19 | +/** |
| 20 | + * The type MultipartFileHashUtils. |
| 21 | + * |
| 22 | + * @since 2025-12-17 |
| 23 | + */ |
| 24 | +public class MultipartFileHashUtils { |
| 25 | + |
| 26 | + /** |
| 27 | + * 计算MultipartFile的MD5哈希 |
| 28 | + */ |
| 29 | + public static String getMultipartFileMD5(MultipartFile file) throws Exception { |
| 30 | + return getMultipartFileHash(file, "MD5"); |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * 计算MultipartFile的SHA-256哈希 |
| 35 | + */ |
| 36 | + public static String getMultipartFileSHA256(MultipartFile file) throws Exception { |
| 37 | + return getMultipartFileHash(file, "SHA-256"); |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * 通用方法:计算MultipartFile的哈希值 |
| 42 | + */ |
| 43 | + public static String getMultipartFileHash(MultipartFile file, String algorithm) |
| 44 | + throws Exception { |
| 45 | + |
| 46 | + MessageDigest digest = MessageDigest.getInstance(algorithm); |
| 47 | + |
| 48 | + try (InputStream inputStream = file.getInputStream()) { |
| 49 | + byte[] buffer = new byte[8192]; |
| 50 | + int bytesRead; |
| 51 | + |
| 52 | + while ((bytesRead = inputStream.read(buffer)) != -1) { |
| 53 | + digest.update(buffer, 0, bytesRead); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return bytesToHex(digest.digest()); |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * 字节数组转十六进制字符串 |
| 62 | + */ |
| 63 | + private static String bytesToHex(byte[] bytes) { |
| 64 | + StringBuilder hexString = new StringBuilder(); |
| 65 | + for (byte b : bytes) { |
| 66 | + String hex = Integer.toHexString(0xff & b); |
| 67 | + if (hex.length() == 1) { |
| 68 | + hexString.append('0'); |
| 69 | + } |
| 70 | + hexString.append(hex); |
| 71 | + } |
| 72 | + return hexString.toString(); |
| 73 | + } |
| 74 | +} |
0 commit comments