文件 SHA-256 加密

master
tangwenkang 2023-11-06 19:51:26 +08:00
parent f27d8cdb7d
commit 8981f0f168
1 changed files with 29 additions and 0 deletions

View File

@ -35,7 +35,10 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -250,6 +253,9 @@ public class VideoServiceImpl implements VideoService {
String filePath = localPath + File.separator + "D:\\uploadVideo" + File.separator + filename; String filePath = localPath + File.separator + "D:\\uploadVideo" + File.separator + filename;
// 创建本地文件对象 // 创建本地文件对象
File localFile = new File(filePath); File localFile = new File(filePath);
// 计算文件的 SHA-256 哈希值比MD5加密更安全
String fileMD5 = calculateFileSHA256(localFile);
System.out.println(fileMD5);
// 检查目录是否存在,如果不存在则创建 // 检查目录是否存在,如果不存在则创建
File localDirectory = localFile.getParentFile(); File localDirectory = localFile.getParentFile();
if (!localDirectory.exists()) { if (!localDirectory.exists()) {
@ -305,6 +311,29 @@ public class VideoServiceImpl implements VideoService {
} }
} }
/**
* SHA-256
* @param file
* @return
*/
private static String calculateFileSHA256(File file) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
digest.update(buffer, 0, bytesRead);
}
byte[] hashBytes = digest.digest();
BigInteger hashValue = new BigInteger(1, hashBytes);
return hashValue.toString(16);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/** /**
* *
* *