Pradeep Sreeram
Pradeep Sreeram

Reputation: 388

Create password protected zip file in Java without creating it on disk

I need a create zip file. It should be password protected. I am using lingala jar. Here is my below. Is there a way to do it? I even tried zipoutstream, couldn't find a way to add password.

@Component
public class FileZipUtils {

    @Value("${candela.email.zip.folder}")
    private String zipBaseDir;

    @Value("${candela.email.zip.encryptionmethod:AES}")
    private String encryptionMethod;

    @Value("${candela.email.zip.encryptionstrength:KEY_STRENGTH_128}")
    private String encryptionStrength;

    private ZipParameters zipParameters;

    @PostConstruct
    private void initializeZipProperties() {
        zipParameters = new ZipParameters();
        zipParameters.setEncryptFiles(true);
        zipParameters.setEncryptionMethod(EncryptionMethod.AES);
        zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_128);
    }

    /*
     * Creates a zipfile in the zipBaseDir location
     */
    public ZipFile createZipFile(String zipFileName,char[] password) {
        return new ZipFile(zipBaseDir + "/" + zipFileName,password);
    }

    /**
     * Adds attachment to Zip file
     */
    public void addAttachementToZip(ZipFile zipFile, ByteArrayResource fileContentInBytes, String fileName)
            throws IOException {
        zipParameters.setFileNameInZip(fileName);
        zipFile.addStream(fileContentInBytes.getInputStream(), zipParameters);
    }

}

Upvotes: 0

Views: 3309

Answers (2)

Pradeep Sreeram
Pradeep Sreeram

Reputation: 388

I think we need to create file on disk.

Upvotes: 0

Abdullajon
Abdullajon

Reputation: 366

The best solution for zip files zip4j lib. (Github Link)

Features:

  • Create, Add, Extract, Update, Remove files from a Zip file
  • Support for streams (ZipInputStream and ZipOutputStream)
  • Read/Write password protected Zip files and streams
  • Support for both AES and Zip-Standard encryption methods
  • Support for Zip64 format
  • Store (No Compression) and Deflate compression method
  • Create or extract files from Split Zip files (Ex: z01, z02,...zip)
  • Support for Unicode file names and comments in zip
  • Progress Monitor - for integration into apps and user facing applications

Upvotes: 1

Related Questions