javax.crypto.BadPaddingException: Given final block not properly padded - VERY VERY URGENT!!!!

I am working on an encryption / decryption function using AES, which performs correctly for one level encryption / decryption. However, when I am trying multiple level (current test case 2 level) encryption / decryption I get the following error: javax.crypto.BadPaddingException: Given final block not properly padded.
I have tried various approaches unsuccessful.
Can you help please?

My code is included below:

FOR ENCRYPTION

public String xEnc(String toEnc, byte[] inKey) throws Exception {

        String message=toEnc;
        SecretKeySpec skeySpec = secKeyG(inKey);

        // Instantiate the cipher
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte [] in = message.getBytes();
        byte[] encrypted =  cipher.doFinal(in);
        encodedParams = cipher.getParameters().getEncoded();
        String out = asHex(encrypted);
       return out;
      }


FOR DECRYPTION

 public static String xDec(byte [] encrypted, byte[] decKey){
          String originalString = "";
        try{
            AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
            params.init(encodedParams);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec skeySpec = secKeyG(decKey);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec,params);
            byte[] original = cipher.doFinal(encrypted);
            originalString = new String(original);
        } catch (Exception e) {
            System.err.println(e.toString());
        }
       return originalString;
     }

Thank you.
romi77Asked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
Make sure that the arrays called 'encrypted' in your encoding and decoding routines really *are* equal
0
 
romi77Author Commented:
PLEASE HELP I NEED THIS YESTERDAY IT IS VERY IMPORTANT!!!!!!!!!!!!!!
THANK YOU

They are equal.
Also I have tried this version with CTR mode with the result below:

/////////////////////////////////RESULT///////////////////////////////////
THIS IS TO_ENC <?xml version='1.0' encoding='UTF-8'?><test><sex>M</sex>      <exam-date>            <year>2005</year><month>August</month><day>13</day></exam-date></test>

////FIRST PASS ENCRYPTION
THIS IS ENC 37dfa8b5a33d3d2a8d8205ae33490bfcb0a3b6bc800c20317f74201db391cd80427820c5c2b6c6b08262282b6622e31e436f1afdcf5f160f2a28dce5c7bcb14e2e2673bc5a3d113bab78b52e905537a488fc43f02298bf4b517004ef8e6b2648e00ebd28c10fff7a03ddb5599127bd1ad4b87977912da2022cc7986eab5386c101fef153bfe642a8b446458070f0b72ade77

///SECOND PASS ENCRYPTION
THIS IS ENC c38d698a9d6e508326ae09c0799172a060cc5527b8fa518cac5ccbc53f368c577a2f8f1aaa43113efffc21ae41a7fb148c448a09a525119ecfbf215cf0d7e24ae6f2a98390ea6e0363bcf51a0feca6e044e229fb6bd932c3da04a4e4a1d86f9f5ab5371d91a7441c89c49c0a16b9ef69fd078444592d35179410803d17be11a68a608a300551d333b65d7ee227829fd296d90c04b825e036f7e04ed4bc743fbf311f87eae022c61a2c166c0581d4f9722dcb1a6bb6e3e859489ddf7eb75bc13093dfa1e0f08fbe3ac438148f82fffbd1c333cba88daf7ffcb59fdd7561b32fc9f02a6520ff7ec76e6b5260a0c2f299c39791a9ce2436dc66c04914315b25bb65773a4cb4a66e390d601c0ddbbe2efc830ef3daa01905f8f33a0e21e088fa522b8b92c757

///FIRST PASS DECRYPTION - WORKS GOOD SAME AS FIRST PASS ENCRYPTION
THIS IS DEC 37dfa8b5a33d3d2a8d8205ae33490bfcb0a3b6bc800c20317f74201db391cd80427820c5c2b6c6b08262282b6622e31e436f1afdcf5f160f2a28dce5c7bcb14e2e2673bc5a3d113bab78b52e905537a488fc43f02298bf4b517004ef8e6b2648e00ebd28c10fff7a03ddb5599127bd1ad4b87977912da2022cc7986eab5386c101fef153bfe642a8b446458070f0b72ade77

/// SECOND PASS DECRYPTION - GIBBERISH EVEN THOUGH THE INPUT BYTE[] IS SAME AS THE OUTPUT OF ENCRYPTION FUNCTION AND KEY IS THE SAME

THIS IS DEC ?Jåüð2m³"g      ¯í;ÐÜæyÄN¶ ÐÜ$õ      9ÈæH9#’Uvt:j?¸»ëôþc?ºb²Ä¨Š¨JÕL¬GojVõ?À?™¾Z$      t¢o9ݔŮå¾M¨:-ñ—´~àÌ !KSGíö{EK¬[;a|J2¬ö™?;wÖf+ìK„‹=#èî









////////////////ENCRYPTION///////////////////////////////
 public String xEnc(String toEnc, byte[] inKey) throws Exception {

        String message=toEnc;
        SecretKeySpec skeySpec = secKeyG(inKey);

        // Instantiate the cipher
        //Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte [] in = message.getBytes();
        byte[] encrypted =  cipher.doFinal(in);
        intermEncVals.add(encrypted);        
        encodedParams = cipher.getParameters().getEncoded();
        String out = asHex(encrypted);
       return out;
      }

/////////////DECRYPTION///////////////
      public static String xDec(byte [] encrypted, byte[] decKey){
          String originalString = "";
        try{
            AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
            params.init(encodedParams);
            //Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
            SecretKeySpec skeySpec = secKeyG(decKey);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec,params);
            byte[] original = cipher.doFinal(encrypted);
           
            originalString = new String(original);
        } catch (Exception e) {
            System.err.println(e.toString());
        }
       return originalString;
     }
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
CEHJCommented:
What's all this about 'first pass' and 'second pass'?
0
 
romi77Author Commented:
I am encrypting a string with 2 keys. Encrypting with 1st key then encrypting the result with the 2nd key.
0
 
romi77Author Commented:
Hi girionis

I have looked at that post but doesn't seem to have helpful info. I have experienced all that was mentioned there but did not found solution.


It is very frustrating because the byte[] to be decrypted that I input to cipher.dofinal in DecryptMODE- is same as the byte [] I get from cipher.dofinal in EncryptMODE also the key and encoded parameters ( encodedParams = cipher.getParameters().getEncoded(); ) are the same yet the result I get is gibberish.

To add to the insult first pass decryption is working just fine.

I do not understand why would that happen. What am I missing?????
0
 
CEHJCommented:
You are i hope, passing into the second pass, a byte[] from the last one, and not a byte[] from a String formed from the last one?
0
 
romi77Author Commented:
I am storing in a String because there is additional info (text) that I have to add to the result of 1st pass before I encrypt again.
0
 
CEHJCommented:
You can't do that. A byte[] will only make a successful String if it can be encoded. In this case, that's unlikely
0
 
romi77Author Commented:
But the byte [] I am trying to decrypt is the same as the byte[] I have obtained from encryption.

 Also the encoding parameters byte[] i(obtained from encryption via encodedParams = cipher.getParameters().getEncoded();) is  the same.

 At least by visual inspection, and test byte by byte of the 2 byte[]s.

 Is there hidden info about the byte[] that cannot be tested  this way?

 How can I do this then??

 How can I make sure that the byte[] can be encoded?

 And why is workin for 1 pass even though same transformation from byte[] to String and back is done?

 
0
 
girionisCommented:
CEHJ is right, it might not be proper to create a String from byte[] and then a byte[] back from String. Just for a try, do it with the same byte[] without going to String first, and see if it helps.
0
 
CEHJCommented:
This is something like the process that should be occurring. Note that there are no strings involved except before and after the process:

PASS      ACTION
--------------
1.      Pass in byte[](from String), receive byte[](out 1)
2.      Pass in byte[](out 1), receive byte[](out 2)

The result, byte[] (out 2), can then be hex encoded to String
0
 
romi77Author Commented:
My problems is that I can have a scenario like this:

1.  Encrypt String A w/ key 1
2. Concatenate result w/ String B (not encrypted)
3. Encrypt String C w/ key 2
4. Concatenate result w/ result @ step 2
5. Encrypt the whole thing w/ key 3
6. Write to file


The steps 1 - 5 can be arbitrarily combined.

That is why I am not sure how your suggestion would apply.

Can you please address the fact that byte[] (out 1) and byte[] to decrypt are the same content wise and length wise and yet the decryption gives gibberish (w/ CTR mode) or BadPaddingException (w/ CBC mode).

THANK YOU      

0
 
CEHJCommented:
>>2. Concatenate result w/ String B (not encrypted)

At this point errors can start. The point is that 'result' is *not* a String, nor is it the binary representation of a String. So it can't be concatenated
0
 
romi77Author Commented:
Does that mean that the project is impossible to do????????

Can these errors be checked and dealt with?
Isn't there any byte[] transformation to String that can aid me?

How can I work around this issue?


THANK YOU
0
 
CEHJCommented:
You will have to avoid treating as potential strings those byte[] that have not been derived *directly* from strings
0
 
romi77Author Commented:
Since the input to decrypt on the 2nd pass is same as output of encrypt in 1st pass I think my issue is with how the Cipher is initialized.
However, I don't know if I want the Cipher to be the same (same object no init) for every decrypton or different object for each decryption.

Any suggestions?

THANK YOU
0
All Courses

From novice to tech pro — start learning today.