我需要在上传时加密文件,而在下载时解密文件。
我编写了一种逻辑,可以在REST spring应用程序中上载和下载文件,但是无法加密和解密。请检查我的代码
控制器-上传逻辑
x in l1
renameFile提供FileNotFoundException,如何从MultipartFile定义整个路径
服务-下载逻辑
@CrossOrigin(maxAge = 4800, allowCredentials = "false")
@RequestMapping(value = "/multipleSave/{module}/{reminderId}", method = RequestMethod.POST)
public @ResponseBody String uploadMultiple(@RequestParam("file") MultipartFile[] files,
@PathVariable String module,@PathVariable int reminderId,
HttpSession session, HttpServletResponse response, HttpServletRequest request) {
long limit = 2 * 1024 * 1024;
String fileName = null;
String msg = "";
String modulePath="";
modulePath = path+"/"+module;
if(files.length > 5){
throw new FileUploadException("Max number of Files to upload is 5");
}
if (files != null && files.length > 0) {
for (int i = 0; i < files.length; i++) {
try {
if(files[i].getSize() > limit){
throw new FileUploadException("File upload Limit is 2 mb, please check the size");
}
fileName = files[i].getOriginalFilename();
String ext = fileName.substring(fileName.lastIndexOf('.') + 1);
String dateTime = getCurrentDateTime();
String localDate = dateTime.toString().replaceAll("[^0-9]", "");
String renameFile = fileName.substring(0,fileName.lastIndexOf('.'))+"_"+localDate.toString()+"."+ext;
NRICSecurity sec = new NRICSecurity();
sec.encrypt(renameFile,modulePath+"/"+renameFile+".enc");
} catch (Exception e) {
//Exception
}
}
}
}
使用RSA进行加密和解密的方法
public void downloadFile(HttpServletResponse response, int fileId) throws FileNotFoundException, IOException {
FileUpload fileUpload = fileDAO.getFileByFileId(fileId);
if (fileUpload != null) {
try{
new NRICSecurity().decrypt(fileUpload.getFilePath()+"/"+fileUpload.getFileNameOrg()+".enc", fileUpload.getFileName());
}catch(Exception e){
}
Path file = Paths.get(fileUpload.getFilePath(), fileUpload.getFileNameOrg());
if (Files.exists(file)) {
try {
String contentType = Files.probeContentType(file);
response.setContentType(contentType);
response.setHeader("Content-disposition", "attachment; filename=" + fileUpload.getFileName());
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
} catch (IOException ex) {
}
} else {
response.sendError(404, new FileNotFoundException().getMessage());
}
} else {
response.sendError(404, new FileNotFoundException().getMessage());
}
}
如果我使用完整路径传递inFile和outFile,则加密和解密方法有效,在上载时,我无法从MultiPartFile []文件获取路径,如果我尝试下载,则只能在浏览器中而不是在服务器位置。