Search code examples
javazipjsch

password protected zip file issue


User upload the file, i need to password protect the file and then zip it put in a storage server which is different from the server where my code is running. So i use AESEncrypter to encrypt the file and jcraft.jsch.ChannelSftp to transfer the file to the server.

public ResponseEntity<ResponseWrapper> uploadFile(@RequestParam("uploads") MultipartFile file) throws Exception {
    FileOutputStream fos = new FileOutputStream("outputfile.zip");
    AESEncrypter aesEncrypter = new AESEncrypterBC();
    aze=new AesZipFileEncrypter(fos, aesEncrypter);
    aze.add(file.getOriginalFilename(), file.getInputStream(), "test123");

    JSch ssh = new JSch();
    Session session = ssh.getSession("username", "Servername", 22);

    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.setPassword("*****");
    session.connect();
    Channel channel = session.openChannel("sftp");
    channel.connect();

    sftp = (ChannelSftp) channel;
    sftpChannel.put(file.getInputStream(), "/storedfiles/outputfile.zip");
}

File is getting transferred to the server, but when i download that transferred file and try to open it says "Errors were found opening ".." you cannot extract file.. do you want to fix the problems". Not sure why i am getting this issue, also it creates a file in local server, which line is causing that?

I tried replacing this line

aze=new AesZipFileEncrypter(fos, aesEncrypter);

with

aze=new AesZipFileEncrypter("outputfile.zip", aesEncrypter); 

but dint work.


Solution

  • I placed the file in remote server, read that in output stream and then password protected, solved my issue.

    public ResponseEntity<ResponseWrapper> uploadFile(@RequestParam("uploads") MultipartFile file) throws Exception {
    JSch ssh = new JSch();
    Session session = ssh.getSession("username", "Servername", 22);
    
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.setPassword("*****");
    session.connect();
    Channel channel = session.openChannel("sftp");
    channel.connect();
    
    sftp = (ChannelSftp) channel;
    OutputStream os = sftp.put("/storedfiles/outputfile.zip");
    
    AESEncrypter aesEncrypter = new AESEncrypterBC();
    aze=new AesZipFileEncrypter(os, aesEncrypter);
    aze.add(file.getOriginalFilename(), file.getInputStream(), "test123");
    if(aze != null) {
     aze.close();
    }    
    }