Solved

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

Posted on 2006-07-14
20
8,753 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 
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
 
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

730 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