سؤال

I'm trying to decrypt the content of a file bigger than 1k for a "RETR" action of an FTP Client and I'm encountering this kind of exception.

   javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.DESCipher.engineDoFinal(DESCipher.java:314)
at javax.crypto.Cipher.doFinal(Cipher.java:2145)

This is the code that is giving me problem:

    byte[] encontent = new byte[0];
    byte[] buff = new byte[1024];
    int k = -1;
    while((k = bis.read(buff, 0, buff.length)) > -1) {
    byte[] tbuff = new byte[encontent.length + k]; // temp buffer size = bytes already  read + bytes last read
    System.arraycopy(encontent, 0, tbuff, 0, encontent.length); // copy previous bytes
    System.arraycopy(buff, 0, tbuff, encontent.length, k);  // copy current lot
    encontent = tbuff; // call the temp buffer as your result buff
    }
     System.out.println(encontent.length + " bytes read.");
     byte [] plain = dcipher.doFinal(encontent, 0,encontent.length);

The length of the byte array encontent is always an 8-bit multple, because it is the result of a previous encryption.

Here it's the code that starts the operation from server side:

  public void download (String pathfile)
 {
       Socket DataSock = null;
    try {
            DataSock = new Socket (clientAddr, TRANSMISSION_PORT);
            if (DataSock.isConnected())
            {
                BufferedOutputStream bos = new BufferedOutputStream (DataSock.getOutputStream());
                int size=0;
                int blocks=0;
                int resto=0;
                if (pathfile.endsWith(".txt"))
                {
                    String text = readTxtFile (pathfile);
                    byte [] encontent = ecipher.doFinal(text.getBytes("UTF8"));
                    sendFile (bos,encontent);
                } else {
                    byte [] content = readFile (pathfile);
                    byte [] encontent = ecipher.doFinal(content);
                    sendFile (bos, content);
                }
            }

    } catch (Exception e)
    {
        e.printStackTrace();
    } finally {
        try {
        DataSock.close();
    } catch (Exception e)
    {
        e.printStackTrace();
    }
    }
}
هل كانت مفيدة؟

المحلول

The final block must contain 8 bytes. If it does not, one has to pad until its 8 bytes wide. Your assumption is wrong. Have a look at https://stackoverflow.com/a/10427679/867816

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top