0

I am using the ftpclient for java in which i want to encrypt a file and decrypt it back again.

The encryption was done successfully using the below code:

String s= EnumerationsQms.ReturnStatus.SUCCESS.getreturnstatus();
int read;

FTPConfig objFTP = (FTPConfig)getHibernateTemplate().find(" from FTPConfig where sstatus='A'").get(3);

FTPClient ftpclient = new FTPClient();

ftpclient.connect(objFTP.getshost(),objFTP.getNport());

logger.info("objFTP.getsip()"+objFTP.getsip());


boolean strue = ftpclient.login(objFTP.getsusername(),objFTP.getspassword());

logger.info("objFTP.getsusername()"+objFTP.getsusername());

logger.info("objFTP.getspassword()"+objFTP.getspassword());
ftpclient.enterLocalPassiveMode();

ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

if(strue)
{
    String st =  GeneralFunctionDAOImpl.getAbsolutePath() + objDbFileStorage.getsFileName();

    logger.info("File Name--->"+st);

    File firstLocalFile = new File(st);           
    String uniquefilename =objDbFileStorage.getnFileImageId() + objDbFileStorage.getsFileName();
    logger.info("uniquefilename"+uniquefilename);

    InputStream inputStream = new FileInputStream(st);
    logger.info("st"+st);

    OutputStream outputStream = ftpclient.storeFileStream(uniquefilename);

    String password = "javapapers";
       PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
       SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndTripleDES");
       SecretKey passwordKey = keyFactory.generateSecret(keySpec);

    byte[] salt = new byte[8];
    Random rnd = new Random();
    rnd.nextBytes(salt);
    int iterations = 100;

    PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);

    Cipher cipher = Cipher.getInstance("PBEWithMD5AndTripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, passwordKey, parameterSpec);
    outputStream.write(salt);

    byte[] input = new byte[64];

    while ((read = inputStream.read(input)) != -1)

    {                   
        byte[] output = cipher.update(input, 0, read);
        if (output != null)
            outputStream.write(output); 

    }   

    byte[] output = cipher.doFinal();
    if (output != null)
        outputStream.write(output);

    inputStream.close();
    outputStream.flush();
    outputStream.close();

    if(ftpclient.isConnected()){
        ftpclient.logout();
        ftpclient.disconnect();
    }
}
return s;

But while decryption it gives the BadPaddingException on code:

String stQuery="from FTPConfig where sstatus='"+Enumerations.MasterStatus_Add+"'";
List<FTPConfig> lstftp=getHibernateTemplate().find(stQuery);

FTPClient ftp=new FTPClient();

ftp.connect(lstftp.get(3).getshost(),lstftp.get(3).getNport());
boolean ftpFile=ftp.login(lstftp.get(3).getsusername(), lstftp.get(3).getspassword());

ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();


if(lstDBfile.size()>0)
{
    String filename =nFileImageID+lstDBfile.get(0).getsFileName(); 

    String absolutePath1 = new File("").getAbsolutePath() + Enumerations.UPLOAD_PATH;
    String uniquefilename =  lstDBfile.get(0).getsFileName();
    String st1 = absolutePath1 + uniquefilename;
    String st2 = absolutePath1 + filename;

    logger.info("**********FTP Storage st1*************"+st1);

    logger.info("**********FTP Storage filename *************"+filename);


    stResult = uniquefilename;
    File file = new File(st1);

    String password = "javapapers";
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
    SecretKeyFactory secretKeyFactory = SecretKeyFactory
            .getInstance("PBEWithMD5AndTripleDES");
    SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);

    InputStream inputStream = ftp.retrieveFileStream(filename);

    OutputStream oufil= new FileOutputStream(st2);
    int c=0;
    while((c=inputStream.read())!=-1)
    {
        oufil.write(c);
    }
    oufil.close();
    ByteArrayInputStream filein = new ByteArrayInputStream(oufil.toString().getBytes());


    byte[] salt = new byte[8];
    filein.read(salt);

    PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 100);

    Cipher cipher = Cipher.getInstance("PBEWithMD5AndTripleDES");


    cipher.init(Cipher.DECRYPT_MODE, secretKey, pbeParameterSpec);

    OutputStream outputStream2 = new FileOutputStream(file);
    long start = System.currentTimeMillis();

    byte[] bytesArray = new byte[64];
    int bytesRead = -1;
    while ((bytesRead = filein.read(bytesArray)) != -1) {

        byte[] output = cipher.update(bytesArray, 0, bytesRead);
        if (output != null)
            outputStream2.write(output);
        outputStream2.write(output);
    }
    byte[] output = cipher.doFinal(); 

    if (output != null)
        outputStream2.write(output);




    boolean download  = ftp.completePendingCommand();
    if (download)
    {  
        System.out.println("File downloaded successfully !");  
        logger.info("file downloaded successfully with "
                + (System.currentTimeMillis() - start) + "ms");
    } 
    else 
    {  
        System.out.println("Error in downloading file !");  
    }  
    outputStream2.flush();
    outputStream2.close();
    inputStream.close();

I get the exception on byte[] output = cipher.doFinal();

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Ash Win
  • 115
  • 1
  • 10

1 Answers1

0

Have a look at When Decrypting Image, gives javax.crypto.BadPaddingException: pad block corrupted Android to see if that helps. It is a bit general, but may point you in the right direction.

Community
  • 1
  • 1
rossum
  • 15,344
  • 1
  • 24
  • 38
  • That's not exactly an answer as we like to see here. Either make it a comment on the question or summarize the contents into your answer. – Artjom B. Apr 23 '15 at 10:24
  • I referenced an existing answer. I saw little point in copying the text rather than passing a reference. – rossum Apr 23 '15 at 10:40
  • Why not vote to close as duplicate? If the answer fits, there is no need to copy it. If it doesn't fit exactly, you still should either make a proper answer or convert to comment. – Artjom B. Apr 23 '15 at 10:43