feat:实现文件加解密

This commit is contained in:
czhqwer
2025-04-04 11:36:27 +08:00
parent eba4b945a4
commit 35bbf7150a
7 changed files with 238 additions and 70 deletions
@@ -6,22 +6,23 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.io.File;
import java.util.List; import java.util.List;
@Slf4j @Slf4j
@RequestMapping("/localFile") @RequestMapping("/localFile")
@RestController @RestController
public class LocalSearchController { public class LocalFileController {
@Resource @Resource
private ILocalFileService fileSearchService; private ILocalFileService localFileService;
/** /**
* 获取系统磁盘列表 * 获取系统磁盘列表
*/ */
@GetMapping("/getDrives") @GetMapping("/getDrives")
public Result<?> getDrives() { public Result<?> getDrives() {
return Result.success(fileSearchService.getDrives()); return Result.success(localFileService.getDrives());
} }
/** /**
@@ -29,7 +30,7 @@ public class LocalSearchController {
*/ */
@PostMapping("/buildIndex") @PostMapping("/buildIndex")
public Result<?> buildIndex(@RequestBody List<String> drives) { public Result<?> buildIndex(@RequestBody List<String> drives) {
return Result.success(fileSearchService.buildIndex(drives)); return Result.success(localFileService.buildIndex(drives));
} }
/** /**
@@ -37,7 +38,7 @@ public class LocalSearchController {
*/ */
@GetMapping("/search") @GetMapping("/search")
public Result<?> search(@RequestParam String keyword) { public Result<?> search(@RequestParam String keyword) {
return Result.success(fileSearchService.searchFiles(keyword)); return Result.success(localFileService.searchFiles(keyword));
} }
/** /**
@@ -66,10 +67,34 @@ public class LocalSearchController {
) { ) {
// 避免直接输入磁盘进去全盘扫描 // 避免直接输入磁盘进去全盘扫描
if (path.length() == 2 && path.endsWith(":")) { if (path.length() == 3 && path.endsWith(":\\") && maxDepth != 1) {
return Result.error("请选择目录"); return Result.error("请选择目录");
} }
return Result.success(fileSearchService.getFileTree(path, showFiles, showFolders, maxDepth)); return Result.success(localFileService.getFileTree(path, showFiles, showFolders, maxDepth));
}
@PostMapping("/encrypt")
public Result<?> encryptFile(@RequestParam String filePath, @RequestParam String password) {
File file = new File(filePath);
if (!file.exists()) {
return Result.error("文件不存在");
}
if (file.isDirectory()) {
return Result.error("不能加密目录,请选择文件");
}
return Result.success(localFileService.encryptFile(filePath, password));
}
@PostMapping("/decrypt")
public Result<?> decryptFile(@RequestParam String filePath, @RequestParam String password) {
File file = new File(filePath);
if (!file.exists()) {
return Result.error("文件不存在");
}
if (file.isDirectory()) {
return Result.error("不能解密目录,请选择文件");
}
return Result.success(localFileService.decryptFile(filePath, password));
} }
} }
@@ -3,6 +3,7 @@ package cn.czh.service;
import cn.czh.dto.FileNode; import cn.czh.dto.FileNode;
import cn.czh.dto.IndexResult; import cn.czh.dto.IndexResult;
import java.io.IOException;
import java.util.List; import java.util.List;
public interface ILocalFileService { public interface ILocalFileService {
@@ -15,4 +16,7 @@ public interface ILocalFileService {
FileNode getFileTree(String path, boolean showFiles, boolean showFolders, int maxDepth); FileNode getFileTree(String path, boolean showFiles, boolean showFolders, int maxDepth);
String encryptFile(String filePath, String password);
String decryptFile(String filePath, String password);
} }
@@ -1,5 +1,6 @@
package cn.czh.service.impl; package cn.czh.service.impl;
import cn.czh.base.BusinessException;
import cn.czh.dto.FileNode; import cn.czh.dto.FileNode;
import cn.czh.dto.IndexResult; import cn.czh.dto.IndexResult;
import cn.czh.service.ILocalFileService; import cn.czh.service.ILocalFileService;
@@ -9,7 +10,16 @@ import org.springframework.stereotype.Service;
import javax.annotation.PreDestroy; import javax.annotation.PreDestroy;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.io.File; import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.SecureRandom;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -20,6 +30,13 @@ public class LocalFileServiceImpl implements ILocalFileService {
@Resource @Resource
private FileSearchUtil fileSearchUtil; private FileSearchUtil fileSearchUtil;
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
private static final int KEY_LENGTH = 256;
private static final int ITERATION_COUNT = 65536;
private static final int SALT_LENGTH = 16;
@PreDestroy @PreDestroy
public void destroy() { public void destroy() {
log.info("关闭 FileSearchUtil 资源..."); log.info("关闭 FileSearchUtil 资源...");
@@ -117,4 +134,126 @@ public class LocalFileServiceImpl implements ILocalFileService {
} }
return node; return node;
} }
@Override
public String encryptFile(String filePath, String password) {
Path path = Paths.get(filePath);
if (!Files.exists(path)) {
throw new BusinessException("文件未找到: " + filePath);
}
String encryptedFilePath = filePath + ".encrypted";
Path encryptedPath = Paths.get(encryptedFilePath);
if (Files.exists(encryptedPath)) {
throw new BusinessException("加密文件已存在: " + encryptedFilePath);
}
try {
byte[] salt = new byte[SALT_LENGTH];
new SecureRandom().nextBytes(salt);
SecretKey key = generateKey(password, salt);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, key);
try (InputStream in = Files.newInputStream(path);
OutputStream out = Files.newOutputStream(encryptedPath)) {
out.write(salt);
byte[] iv = cipher.getIV();
out.write(iv);
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
byte[] output = cipher.update(buffer, 0, bytesRead);
if (output != null) {
out.write(output);
}
}
byte[] outputBytes = cipher.doFinal();
if (outputBytes != null) {
out.write(outputBytes);
}
}
return encryptedFilePath;
} catch (Exception e) {
try {
Files.deleteIfExists(encryptedPath);
} catch (IOException ex) {
log.error("删除加密失败的文件时出错: {}", ex.getMessage(), ex);
}
throw new BusinessException("文件加密失败", e);
}
}
@Override
public String decryptFile(String filePath, String password) {
Path path = Paths.get(filePath);
if (!Files.exists(path)) {
throw new BusinessException("文件未找到: " + filePath);
}
String decryptedFilePath = filePath.replace(".encrypted", "");
Path decryptedPath = Paths.get(decryptedFilePath);
if (Files.exists(decryptedPath)) {
throw new BusinessException("解密文件已存在: " + decryptedFilePath);
}
try {
// Read salt and IV
byte[] salt = new byte[SALT_LENGTH];
byte[] iv = new byte[16];
try (InputStream in = Files.newInputStream(path)) {
if (in.read(salt) != SALT_LENGTH) {
throw new BusinessException("加密文件格式无效");
}
if (in.read(iv) != 16) {
throw new BusinessException("加密文件格式无效");
}
}
SecretKey key = generateKey(password, salt);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, key, new javax.crypto.spec.IvParameterSpec(iv));
try (InputStream in = Files.newInputStream(path);
OutputStream out = Files.newOutputStream(decryptedPath)) {
in.skip(SALT_LENGTH + 16);
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
byte[] output = cipher.update(buffer, 0, bytesRead);
if (output != null) {
out.write(output);
}
}
byte[] outputBytes = cipher.doFinal();
if (outputBytes != null) {
out.write(outputBytes);
}
}
return decryptedFilePath;
} catch (Exception e) {
// 删除已生成的解密文件
try {
Files.deleteIfExists(decryptedPath);
} catch (IOException ex) {
log.error("删除解密失败的文件时出错: {}", ex.getMessage(), ex);
}
throw new BusinessException("文件解密失败", e);
}
}
private SecretKey generateKey(String password, byte[] salt) throws Exception {
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, ITERATION_COUNT, KEY_LENGTH);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
byte[] keyBytes = factory.generateSecret(keySpec).getEncoded();
return new SecretKeySpec(keyBytes, ALGORITHM);
}
} }
@@ -31,6 +31,7 @@
<el-radio <el-radio
v-model="selectedPath" v-model="selectedPath"
@change="handleRadioChange(data)" @change="handleRadioChange(data)"
:disabled="!allowSelectFolder && data.folder"
></el-radio> ></el-radio>
<i :class="data.folder ? 'el-icon-folder' : 'el-icon-document'"></i> <i :class="data.folder ? 'el-icon-folder' : 'el-icon-document'"></i>
<span>{{ node.label }}</span> <span>{{ node.label }}</span>
@@ -54,6 +55,10 @@ export default {
showFiles: { showFiles: {
type: Boolean, type: Boolean,
default: true default: true
},
allowSelectFolder: {
type: Boolean,
default: true
} }
}, },
data() { data() {
@@ -138,6 +143,9 @@ export default {
} }
}, },
handleRadioChange(data) { handleRadioChange(data) {
if (!this.allowSelectFolder && data.folder) {
return;
}
this.selectedPath = data.path; this.selectedPath = data.path;
this.isDropdownVisible = false; this.isDropdownVisible = false;
this.$emit('change', data.path); this.$emit('change', data.path);
@@ -214,4 +222,9 @@ export default {
.custom-tree-node i.el-icon-document { .custom-tree-node i.el-icon-document {
color: #909399; color: #909399;
} }
:deep(.el-radio__label) {
width: 0;
padding: 0;
}
</style> </style>
@@ -2,26 +2,22 @@
<div class="file-encrypt-container"> <div class="file-encrypt-container">
<el-form :model="form" label-width="100px"> <el-form :model="form" label-width="100px">
<!-- 文件上传 --> <!-- 文件上传 -->
<el-form-item label="上传文件"> <el-form-item label="文件">
<el-upload <SelectDir
ref="upload" v-model="form.file"
action="" @change="handlePathChange"
:http-request="handleUpload" :showFiles="true"
:before-upload="beforeUpload" :allowSelectFolder="false"
:multiple="false" style="width: 400px; margin-right: 10px;"
:show-file-list="false" />
>
<el-button type="primary">点击上传文件</el-button>
</el-upload>
</el-form-item> </el-form-item>
<!-- 加密密钥 --> <!-- 加密密钥 -->
<el-form-item label="密钥"> <el-form-item label="密钥">
<el-input <el-input
v-model="form.key" v-model="form.key"
placeholder="请输入加密/解密密钥" placeholder="请输入密钥"
style="width: 300px;" style="width: 400px;"
show-password
></el-input> ></el-input>
</el-form-item> </el-form-item>
@@ -31,56 +27,34 @@
<el-button type="warning" @click="decryptFile" :disabled="!form.file || !form.key">解密文件</el-button> <el-button type="warning" @click="decryptFile" :disabled="!form.file || !form.key">解密文件</el-button>
</el-form-item> </el-form-item>
</el-form> </el-form>
<!-- 下载链接 -->
<div v-if="downloadUrl" class="download-section">
<el-link :href="downloadUrl" type="primary" :download="downloadFileName">点击下载处理后的文件</el-link>
</div>
</div> </div>
</template> </template>
<script> <script>
import { encryptFile, decryptFile } from '@/utils/api'; import { encryptFile, decryptFile } from '@/utils/api';
import SelectDir from '@/components/SelectDir/SelectDir.vue';
export default { export default {
name: 'FileEncrypt', name: 'FileEncrypt',
components: {
SelectDir
},
data() { data() {
return { return {
form: { form: {
file: null, // 上传的文件对象 file: '',
key: '', key: '',
}, },
downloadUrl: '', // 下载链接
downloadFileName: '', // 下载文件名
}; };
}, },
methods: { methods: {
// 文件上传前校验
beforeUpload(file) {
this.form.file = file;
this.downloadUrl = ''; // 清空之前的下载链接
return false; // 阻止默认上传,使用自定义 http-request
},
// 自定义上传处理
async handleUpload(option) {
// 文件已通过 beforeUpload 保存到 form.file,无需额外处理
console.log('handleUpload', option);
},
// 加密文件 // 加密文件
async encryptFile() { async encryptFile() {
if (!this.validateForm()) return; if (!this.validateForm()) return;
const formData = new FormData();
formData.append('file', this.form.file);
formData.append('key', this.form.key);
try { try {
const res = await encryptFile(formData); const res = await encryptFile(this.form.file, this.form.key);
if (res.code === 200) { if (res.code === 200) {
this.handleFileResponse(res.data, this.form.file.name + '.enc'); this.$message.success('文件加密成功,请前往目录查看');
this.$message.success('文件加密成功,请下载');
} else {
this.$message.error(res.msg || '加密失败');
} }
} catch (error) { } catch (error) {
this.$message.error('加密请求失败'); this.$message.error('加密请求失败');
@@ -91,34 +65,20 @@ export default {
async decryptFile() { async decryptFile() {
if (!this.validateForm()) return; if (!this.validateForm()) return;
const formData = new FormData();
formData.append('file', this.form.file);
formData.append('key', this.form.key);
try { try {
const res = await decryptFile(formData); const res = await decryptFile(this.form.file, this.form.key);
if (res.code === 200) { if (res.code === 200) {
const originalName = this.form.file.name.replace('.enc', ''); this.$message.success('文件解密成功,请前往目录查看');
this.handleFileResponse(res.data, originalName);
this.$message.success('文件解密成功,请下载');
} else {
this.$message.error(res.msg || '解密失败');
} }
} catch (error) { } catch (error) {
this.$message.error('解密请求失败'); this.$message.error('解密请求失败');
console.error(error); console.error(error);
} }
}, },
// 处理后端返回的文件
handleFileResponse(blob, fileName) {
const url = window.URL.createObjectURL(blob);
this.downloadUrl = url;
this.downloadFileName = fileName;
},
// 表单校验 // 表单校验
validateForm() { validateForm() {
if (!this.form.file) { if (!this.form.file) {
this.$message.warning('请上传文件'); this.$message.warning('请选择文件');
return false; return false;
} }
if (!this.form.key) { if (!this.form.key) {
@@ -133,6 +93,7 @@ export default {
<style scoped> <style scoped>
.file-encrypt-container { .file-encrypt-container {
height: 400px;
padding: 20px; padding: 20px;
} }
@@ -122,8 +122,6 @@ export default {
this.updateTextTree(); this.updateTextTree();
}); });
this.$message.success('文件树获取成功'); this.$message.success('文件树获取成功');
} else {
this.$message.error(res.msg || '获取文件树失败');
} }
} catch (error) { } catch (error) {
this.$message.error('请求失败,请检查网络或路径'); this.$message.error('请求失败,请检查网络或路径');
+28
View File
@@ -325,6 +325,32 @@ const getFileTree = (path, showFiles, showFolders, maxDepth) => {
}); });
} }
/**
* 加密文件
* @param {string} filePath
* @param {string} password
* @returns
*/
const encryptFile = (filePath, password) => {
const formData = new FormData();
formData.append('filePath', filePath);
formData.append('password', password);
return http.post("/localFile/encrypt", formData);
}
/**
* 解密文件
* @param {string} filePath
* @param {string} password
* @returns
*/
const decryptFile = (filePath, password) => {
const formData = new FormData();
formData.append('filePath', filePath);
formData.append('password', password);
return http.post("/localFile/decrypt", formData);
}
export { export {
getUploadProgress, getUploadProgress,
createMultipartUpload, createMultipartUpload,
@@ -350,5 +376,7 @@ export {
localFileSearch, localFileSearch,
openDir, openDir,
getFileTree, getFileTree,
encryptFile,
decryptFile,
httpExtra httpExtra
}; };