修复漏洞问题

This commit is contained in:
sh
2026-05-02 20:41:29 +08:00
parent 0b3a3b4da6
commit 35feb9a147
7 changed files with 235 additions and 10 deletions

View File

@@ -0,0 +1,84 @@
package com.ruoyi.cms.util.file;
import org.springframework.web.multipart.MultipartFile;
import java.util.Arrays;
import java.util.List;
/**
* 文件校验
*/
public class FileValid {
/**
* 白名单配置
*/
final static List<String> allowedExt = Arrays.asList(
"jpg", "jpeg", "png", "gif", "pdf",
"doc", "docx", "wps",
"xls", "xlsx",
"ppt", "pptx"
);
/**
* 支持的MIME类型
*/
final static List<String> allowedMime = Arrays.asList(
"image/jpeg", "image/png", "image/gif", "application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.ms-works", // wps
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.ms-powerpoint",
"application/vnd.openxmlformats-officedocument.presentationml.presentation"
);
/**
* 魔数校验
*/
final static List<String> allowedMagic = Arrays.asList(
"ffd8ffe0", "ffd8ffe1", // jpg
"89504e47", // png
"47494638", // gif
"25504446" // pdf
);
/**
* 文件类型 + MIME + 魔数 三重验证
* @param file
* @return
*/
public static boolean validateFile(MultipartFile file) {
try {
// 白名单配置
String originalFilename = file.getOriginalFilename().toLowerCase();
String contentType = file.getContentType();
String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
// 扩展名 + MIME 校验
if (!allowedExt.contains(ext) || !allowedMime.contains(contentType)) {
return false;
}
return true;
} catch (Exception e) {
return false;
}
}
/**
* 字节转16进制魔数校验用
* @param bytes
* @return
*/
private static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}