原创:欢迎分享,转载请保留出处。任何不保留此声明的转载都是抄袭。
最近领导交给自己一个需求,要求将服务器上的多个文件加密打包下载,经过多天的努力,终于可以成功下载
加密解密工具类
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.*;
import java.security.Key;
import java.util.Base64;
/**
* DES加密解密字符串或文件
* @author lixy940
* @data 2021/2/10 08:59
* @version 1.0
*/
public class DESUtil {
/**
* 偏移变量,固定占8位字节,根据需要设置
*/
private final static String IV_PARAMETER = "xxxxxxxx";
/**
* 密钥算法
*/
private static final String ALGORITHM = "DES";
/**
* 加密/解密算法-工作模式-填充模式
*/
private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";
/**
* 默认编码
*/
private static final String CHARSET = "utf-8";
/**
* 生成key
*
* @param password
* @return
* @throws Exception
*/
private static Key generateKey(String password) throws Exception {
DESKeySpec dks = new DESKeySpec(password.getBytes(CHARSET));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
return keyFactory.generateSecret(dks);
}
/**
* DES加密字符串
*
* @param password 加密密码,长度不能够小于8位
* @param data 待加密字符串
* @return 加密后内容
*/
public static String encrypt(String password, String data) {
if (password == null || password.length() < 8) {
throw new RuntimeException("加密失败,key不能小于8位");
}
if (data == null)
return null;
try {
Key secretKey = generateKey(password);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] bytes = cipher.doFinal(data.getBytes(CHARSET));
//JDK1.8及以上可直接使用Base64,JDK1.7及以下可以使用BASE64Encoder
//Android平台可以使用android.util.Base64
return new String(Base64.getEncoder().encode(bytes));
} catch (Exception e) {
e.printStackTrace();
return data;
}
}
/**
* DES解密字符串
*
* @param password 解密密码,长度不能够小于8位
* @param data 待解密字符串
* @return 解密后内容
*/
public static String decrypt(String password, String data) {
if (password == null || password.length() < 8) {
throw new RuntimeException("加密失败,key不能小于8位");
}
if (data == null)
return null;
try {
Key secretKey = generateKey(password);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET))), CHARSET);
} catch (Exception e) {
e.printStackTrace();
return data;
}
}
/**
* DES加密文件
*
* @param password 加密密码,长度不能够小于8位
* @param srcFile 待加密的文件
* @param destFile 加密后存放的文件路径
* @return 加密后的文件路径
*/
public static String encryptFile(String password, String srcFile, String destFile) {
if (password == null || password.length() < 8) {
throw new RuntimeException("加密失败,key不能小于8位");
}
try {
IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, generateKey(password), iv);
InputStream is = new FileInputStream(srcFile);
OutputStream out = new FileOutputStream(destFile);
CipherInputStream cis = new CipherInputStream(is, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = cis.read(buffer)) > 0) {
out.write(buffer, 0, r);
}
cis.close();
is.close();
out.close();
return destFile;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* DES解密文件
*
* @param password 解密密码,长度不能够小于8位
* @param srcFile 已加密的文件
* @param destFile 解密后存放的文件路径
* @return 解密后的文件路径
*/
public static String decryptFile(String password, String srcFile, String destFile) {
if (password == null || password.length() < 8) {
throw new RuntimeException("加密失败,key不能小于8位");
}
try {
File file = new File(destFile);
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, generateKey(password), iv);
InputStream is = new FileInputStream(srcFile);
OutputStream out = new FileOutputStream(destFile);
CipherOutputStream cos = new CipherOutputStream(out, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = is.read(buffer)) >= 0) {
cos.write(buffer, 0, r);
}
cos.close();
is.close();
out.close();
return destFile;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* DES加密流
*
* @param password 加密密码,长度不能够小于8位
* @param is 待加密的流
* @return 加密后的返回的流
*/
public static InputStream encryptStream(String password,InputStream is) {
if (password == null || password.length() < 8) {
throw new RuntimeException("加密失败,key不能小于8位");
}
try {
IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, generateKey(password), iv);
CipherInputStream cis = new CipherInputStream(is, cipher);
return cis;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* DES解密流
*
* @param password 解密密码,长度不能够小于8位
* @param is 待解密的流
* @return 解密后的文件路径
*/
public static InputStream decryptStream(String password,InputStream is) {
if (password == null || password.length() < 8) {
throw new RuntimeException("加密失败,key不能小于8位");
}
try {
IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, generateKey(password), iv);
CipherInputStream cis = new CipherInputStream(is, cipher);
return cis;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
文件下载controller层
@ApiOperation(value = "下载")
@ApiImplicitParam(name = "id", value = "业务id",required = true)
@GetMapping("/downLoad/{id}")
public void downLoad(@PathVariable("id") Integer id, HttpServletResponse response) {
InputStream is = null;
InputStream isw = null;
ZipOutputStream zos=null;
DataOutputStream os = null;
HttpURLConnection conn=null;
try {
// 控制文件名编码
String fileName = URLEncoder.encode("test-"+ DateUtil.getCurrentDay()+".zip", "UTF-8");
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
// OutputStream os = response.getOutputStream();
zos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
os = new DataOutputStream(zos);
byte[] bytes = null;
/**
* 调用自己实际的业务服务,得到要下载的文件路径
* 可能是远程服务器文件地址,路径也可能在本地服务器上
*/
List<String> pathList = bussinessService.getFilePathList(id);
/*
//远程服务器地址文件下载测速路径
List<String> pathList = new ArrayList<>();
pathList.add("http://archive.apache.org/dist/flink/flink-1.9.3/flink-1.9.3-bin-scala_2.11.tgz");
pathList.add("http://archive.apache.org/dist/spark/spark-2.1.0/spark-2.1.0-bin-hadoop2.3.tgz");*/
for (String path : pathList) {
if (StringUtils.isBlank(path))
continue;
//方式一 文件在远程服务器,http/https路径
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setConnectTimeout(6000);
is = conn.getInputStream();
String name = handlerRemoteName(path);
zos.putNextEntry(new ZipEntry(dto.getType() + '/' + name));
//方式二 文件在本地服务器上,服务器上的路径直接new File,并转为字节流
/* String name =handlerName(path);
is = new FileInputStream(new File(path));
zos.putNextEntry(new ZipEntry(dto.getType() + File.separator + name));*/
//方式三 服务器字符串信息输出
/*String data ="如果需要将内存中的string信息输出为json文件,可取消下面注释";
zos.putNextEntry(new ZipEntry("data.json"));
bytes = data.getBytes(Charset.forName("utf8"));
is = new ByteArrayInputStream(bytes);*/
//流加密
isw = DESUtil.encryptStream(desSecretKey, is);
int len;
byte[] buf = new byte[1024];
while ((len = isw.read(buf)) != -1) {
os.write(buf, 0, len);
}
is.close();
zos.closeEntry();
}
os.flush();
os.close();
isw.close();
zos.close();
} catch (FileNotFoundException ex) {
log.error("FileNotFoundException", ex);
} catch (Exception ex) {
log.error("Exception", ex);
}finally {
if (conn!=null) {
conn.disconnect();
}
if (os!=null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (zos!=null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (isw!=null) {
try {
isw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is!=null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@ApiOperation(value = "解析加密压缩包到本地")
@ApiImplicitParams({
@ApiImplicitParam(name = "sourcePath", value = "压缩包源路径", paramType = "query", dataType = "String")
})
@GetMapping("/parseZip")
public void parseZip(@RequestParam("sourcePath") String sourcePath) {
File srcFile = new File(sourcePath);
InputStream is = null;
InputStream isw = null;
FileOutputStream fos = null;
try {
// 判断源文件是否存在
if (!srcFile.exists()) {
throw new Exception(srcFile.getPath() + "所指文件不存在");
}
String destDirPath = sourcePath.replace(".zip", "");
//创建压缩文件对象
ZipFile zipFile = new ZipFile(srcFile);
//开始解压
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
// 如果是文件夹,就创建个文件夹
if (entry.isDirectory()) {
srcFile.mkdirs();
} else {
// 如果是文件,就先创建一个文件,然后用io流把内容copy过去
File targetFile = new File(destDirPath + File.separator + entry.getName());
// 保证这个文件的父文件夹必须要存在
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// 将压缩文件内容写入到这个文件中
is = zipFile.getInputStream(entry);
//流解密
isw = DESUtil.decryptStream(desSecretKey, is);
fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[1024];
while ((len = isw.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 关流顺序,先打开的后关闭
fos.flush();
fos.close();
isw.close();
is.close();
}
}
zipFile.close();
} catch (Exception e) {
log.error("zip decrypt exception", e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (isw != null) {
try {
isw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 截取文件名称
* @param path
* @return
*/
public String handlerName(String path) {
if (StringUtils.isBlank(path) || !StringUtils.contains(path, File.separator)) {
return "";
}
return path.substring(path.lastIndexOf(File.separator) + 1);
}
/**
* 截取远程文件名称
* @param path
* @return
*/
public String handlerRemoteName(String path) {
if (StringUtils.isBlank(path) || !StringUtils.contains(path, "/")) {
return "";
}
return path.substring(path.lastIndexOf("/") + 1);
}
以上使用方法二从本地服务器上下载文件(即,文件存储在部署的服务器上),如果文件在
远程文件服务器上,可通过工具类RemoteFileUtils调用getStreamFromURL方法请求获取
文件流信息(主要通过http/https),其中 desSecretKey 为加解密密钥 根据自己需求设置