我在byte []数组中有pdf文件。我想压缩它并用密码加密。 我不想创建任何临时文件。但是像zip4j,winzipaes这样的库不支持它。它们仅接受File对象。
编辑: 简单zip的代码:
public static byte[] zipBytes(String filename, byte[] input) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
ZipEntry entry = new ZipEntry(filename);
entry.setSize(input.length);
zos.putNextEntry(entry);
zos.write(input);
zos.closeEntry();
zos.close();
return baos.toByteArray();}
如何添加加密和密码?
答案 0 :(得分:0)
我找到了一些资源,并使其适合我的问题。 将其加载到https://github.com/r331/memzipenc
MemZipEnc.getEncryptZipByte(byte []文件,java.lang.String密码,java.lang.String文件名)这种静态方法可以加密和压缩内存中的单个文件,而无需将文件保存在硬盘上
答案 1 :(得分:0)
有点晚了,但希望这个小片段对别人有所帮助。这是针对Java 7上的zip4j
private byte[] compressFileByZip(byte[] fileBytes, String filenameInZip, String zipFilePassword) throws ZipException {
// Zip into a ByteArrayOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try(ZipOutputStream zos = new ZipOutputStream(baos)) {
ZipParameters zipParameters = new ZipParameters();
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipParameters.setSourceExternalStream(true);
zipParameters.setFileNameInZip(filenameInZip);
// Set the encryption method to AES Zip Encryption
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
zipParameters.setPassword(zipFilePassword);
// Zip, flush and clean up
zos.putNextEntry(null, zipParameters);
zos.write(fileBytes);
zos.flush();
zos.closeEntry();
zos.close();
zos.finish();
} catch(IOException ioe) {
ioe.printStackTrace();
LOG.error("Error writing compressed file", ioe);
}
// Extract zipped file as byte array
byte[] byteCompressedFile = baos.toByteArray();
LOG.info("Zipped successfully");
return byteCompressedFile;
}
关于加密的部分是可选的。