Original: welcome to share, reprint please reserve source. Any reprint that does not retain this statement is plagiarism.Copy the code
Recently, the leader gave himself a demand, the requirements of the server on the multiple files encryption package download, after several days of efforts, finally can be downloaded successfully
Encryption and decryption tool class
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;
}
}
Copy the code
File download controller layer
@apiOperation (value = "download ") @apiImplICITParam (name = "id", Value = "Service 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; 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; /** * call your own actual business service, get the file path to download * may be the remote server file address, Path may also be on the local server * / 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; // Mode 1 file on the remote server, HTTP/HTTPS path 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)); /* String name =handlerName(path); is = new FileInputStream(new File(path)); zos.putNextEntry(new ZipEntry(dto.getType() + File.separator + name)); /*String data =" If you want to output the String information in memory as a JSON file, you can cancel the following comment "; 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 = "parse encrypted compressed package to local ") @apiImplicitParams ({@apiIMPLicitParam (name = "sourcePath", Value = "Compressed package source path ", 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; // Check whether the source file exists if (! Srcfile.exists ()) {throw new Exception(srcfile.getPath () + "the file referred to does not exist "); } String destDirPath = sourcePath.replace(".zip", ""); ZipFile = new ZipFile(srcFile); // Start decompressing Enumeration<? > entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); // Create a folder if (entry.isdirectory ()) {srcfile.mkdirs (); } else {// Create a File and copy the contents to the IO stream File targetFile = new File(destDirPath + file.separator + entry.getName()); // Make sure that the parent folder of this file exists if (! targetFile.getParentFile().exists()) { targetFile.getParentFile().mkdirs(); } targetFile.createNewFile(); // Write the compressed file contents to this file 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); }Copy the code
Download the file from the local server (that is, the file is stored on the deployed server). If the file is stored on the remote file server, The utility class RemoteFileUtils can call the getStreamFromURL method to request to obtain file flow information (mainly through HTTP/HTTPS), where desSecretKey is the encryption and decryption key set according to your requirementsCopy the code