7Z压缩支持加密

import java.io.;
import java.security.
;

import javax.crypto.*;

import org.apache.commons.compress.archivers.ArchiveStreamFactory;

import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;

import org.apache.commons.compress.archivers.sevenz.SevenZFile;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;

import java.security.Provider;

public class SevenZCompressor {

public static void main(String[] args) {

try {

SevenZCompressor comp = new SevenZCompressor();

File inputFile = new File("input");

File outputFile = new File("output.7z");

int compressionLevel = 9; // 设置压缩级别,0为无压缩,9为最高压缩

Key secretKey = generateSecretKey();

comp.compressFolder(inputFile, outputFile, secretKey, compressionLevel);

} catch (Exception e) {

e.printStackTrace();

}

}

public void compressFolder(File folder, File outputFile, Key secretKey, int compressionLevel) throws IOException, NoSuchAlgorithmException {
    OutputStream output-sevenZ = new FileOutputStream(outputFile);
    OutputStream output = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.SEVEN_Z, output-sevenZ);

    output = new CipherOutputStream(output, createCipher(secretKey));
    
    // 设置压缩方法
    SevenZArchiveEntry entry = new SevenZArchiveEntry(folder.getName());
    entry.setMethod(SevenZArchiveEntryMETHODSTORE);
    entry.setCompressionMethod(compressionLevel);
    output.putArchiveEntry(entry);

    // 添加文件或文件夹到压缩文件中
    SevenZFile sevenZFile = new SevenZFile(output-sevenZ);
    sevenZFile.addFile(folder);

    output.closeArchiveEntry();

    output.close();
}

private Cipher createCipher(Key secretKey) throws NoSuchAlgorithmException, NoSuchPaddingException {
    SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), "Blowfish");
    BouncyCastleProvider provider = new BouncyCastleProvider();
    Security.addProvider(provider);
    Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding", provider);
    cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(new byte[16]));
    return cipher;
}

private Key generateSecretKey() throws NoSuchAlgorithmException, InvalidKeyException {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
    keyGenerator.init(128);
    return keyGenerator.generateKey();
}

}

相关推荐
徐*红22 分钟前
java 线程池
java·开发语言
尚学教辅学习资料23 分钟前
基于SSM的养老院管理系统+LW示例参考
java·开发语言·java毕设·养老院
2401_8576363923 分钟前
计算机课程管理平台:Spring Boot与工程认证的结合
java·spring boot·后端
1 9 J25 分钟前
Java 上机实践4(类与对象)
java·开发语言·算法
Code apprenticeship25 分钟前
Java面试题(2)
java·开发语言
憨子周1 小时前
2M的带宽怎么怎么设置tcp滑动窗口以及连接池
java·网络·网络协议·tcp/ip
霖雨3 小时前
使用Visual Studio Code 快速新建Net项目
java·ide·windows·vscode·编辑器
SRY122404193 小时前
javaSE面试题
java·开发语言·面试
Fiercezm3 小时前
JUC学习
java
无尽的大道3 小时前
Java 泛型详解:参数化类型的强大之处
java·开发语言