Solved

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

Posted on 2006-07-14
20
8,713 Views
Last Modified: 2012-06-27
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.
0
Comment
Question by:romi77
  • 8
  • 7
  • 2
20 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 250 total points
ID: 17113729
Make sure that the arrays called 'encrypted' in your encoding and decoding routines really *are* equal
0
 

Author Comment

by:romi77
ID: 17117817
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
 
LVL 35

Assisted Solution

by:girionis
girionis earned 250 total points
ID: 17120214
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17120363
What's all this about 'first pass' and 'second pass'?
0
 

Author Comment

by:romi77
ID: 17123546
I am encrypting a string with 2 keys. Encrypting with 1st key then encrypting the result with the 2nd key.
0
 

Author Comment

by:romi77
ID: 17125289
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 17125384
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
 

Author Comment

by:romi77
ID: 17125445
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 86

Expert Comment

by:CEHJ
ID: 17125618
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
 

Author Comment

by:romi77
ID: 17125815
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
 
LVL 35

Expert Comment

by:girionis
ID: 17128173
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 17128313
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
 

Author Comment

by:romi77
ID: 17128966
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 17129200
>>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
 

Author Comment

by:romi77
ID: 17131717
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 17148707
You will have to avoid treating as potential strings those byte[] that have not been derived *directly* from strings
0
 

Author Comment

by:romi77
ID: 17158716
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

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Java and GPO 11 71
eclipse formatting 6 73
simple java question 3 44
HSSFWorkbook cannot be resolved error 10 50
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now