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();
}
}