This discussion is archived
1 2 Previous Next 20 Replies Latest reply: Sep 18, 2012 7:11 PM by EJP RSS

How to decrypt entered value if Cipher outputsize is different.

Ajay Sharma Newbie
Currently Being Moderated
Hi..

am using AES algorithm in Web Service for encryption and decryption. The outputsize in encryption and decryption are different

i used following code to check it.
int outPutSize = cipher.getOutputSize(len);
I think because of this difference its not decrypting the entered value.
How to solve this issue



Regards,
Ajay
  • 1. Re: How to decrypt entered value if Cipher outputsize is different.
    EJP Guru
    Currently Being Moderated
    The outputsize in encryption and decryption are different
    There's nothing unusual about that. A cipher might for example always produce blocks of 16 bytes for any input length between 1 and 16, via padding.
    I think because of this difference its not decrypting the entered value.
    I doubt that's the reason.
  • 2. Re: How to decrypt entered value if Cipher outputsize is different.
    Ajay Sharma Newbie
    Currently Being Moderated
    Hi..

    So is there any way to solve it. As it must be multiple of 16. Right ?

    Regards,
    Ajay
  • 3. Re: How to decrypt entered value if Cipher outputsize is different.
    EJP Guru
    Currently Being Moderated
    Wrong. I specifically wrote +"for example"+ and +"might."+

    There's not much point in posting here if you're not going to read the responses properly.
  • 4. Re: How to decrypt entered value if Cipher outputsize is different.
    Ajay Sharma Newbie
    Currently Being Moderated
    Ok.. Thanks..

    How do I perform Decryption ? Any way to solve this issue ?


    Regards,
    Ajay
  • 5. Re: How to decrypt entered value if Cipher outputsize is different.
    EJP Guru
    Currently Being Moderated
    How do I perform Decryption ?
    With javax.crypto.Cipher, as you seem to be doing. But I will add that if this has anything to do with your previous thread you should almost certainly be using SSL instead of trying to roll your own.
    Any way to solve this issue ?
    What issue? Zero information has been provided. No details; no encryption code; no decryption code; no test data; no 'expected' vs. 'actual'. Not a real question.

    You're heading for another locked thread at this rate.
  • 6. Re: How to decrypt entered value if Cipher outputsize is different.
    Ajay Sharma Newbie
    Currently Being Moderated
    Hi..

    Here is code

         private static byte[] getKeyBytes(String key) throws UnsupportedEncodingException {
            byte[] keyBytes = new byte[16];
            byte[] parameterKeyBytes = key.getBytes("UTF-8");
            System.arraycopy(parameterKeyBytes, 0, keyBytes, 0, Math.min(parameterKeyBytes.length, keyBytes.length));
    
            return keyBytes;
          }
    Encryption Method Code :
    =================
        public String encrypt(String plainText, String key)// throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{
        {    
            String encryptedValue="";
                      
         try{
                byte[] plainTextbytes = plainText.getBytes("UTF-8");
                byte[] keyBytes = getKeyBytes(key);
                byte[] encryptedByte = encrypt(plainTextbytes,keyBytes, keyBytes);
                encryptedValue = new BASE64Encoder().encode(encryptedByte);
                System.out.println("Encrypted Value = "+encryptedValue);
            }
            catch(Exception e){
                e.getMessage();
            }
            return(encryptedValue);
            
        }
        
        public static byte[] encrypt(byte[] plainText, byte[] key, byte [] initialVector) throws Exception,NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
        {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
           
            SecretKeySpec secretKeySpec = new SecretKeySpec(key,  "AES");
               
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
        
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            
            int len = plainText.length;
            int outPutSize = cipher.getOutputSize(len);
            System.out.println("Out Put Buffer Size in Encrypt = "+ outPutSize); // here output buffer coming is 160 
            System.out.println("Decrypting Final");
        
            
            byte[] plainText1 = cipher.doFinal(plainText);
            
            return plainText1;
        }
    Decryption Method Code:
    ================
         public static String decrypt(String encryptedText, String key)
             throws KeyException, GeneralSecurityException, GeneralSecurityException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException
           {
           
            System.out.println("Inside Decrypt Method ");
             String decryptedValue = "";
             try
             {
                byte[] cipheredBytes = new BASE64Decoder().decodeBuffer(encryptedText);
                System.out.println("Cipher Bytes = "+cipheredBytes);
                byte[] keyBytes = getKeyBytes(key);
                 System.out.println("Key Bytes = "+keyBytes);
                byte[] decryptBytes = decrypt(cipheredBytes, keyBytes, keyBytes);
                 System.out.println("Decrypted Bytes = "+decryptBytes);
                decryptedValue = new String(decryptBytes);
                System.out.println("Decrypted Value in Decrypt method = " + decryptedValue);
             }
             catch (Exception e)
             {
               e.getMessage();
             }
    
             return decryptedValue;
           }
    
         public static byte[] decrypt(byte[] cipherText, byte[] key, byte[] initialVector)
            throws Exception, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
          {
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                         
                SecretKeySpec secretKeySpecy = new SecretKeySpec(key, "AES");
                
             
               IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
                   
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpecy, ivParameterSpec);
            int len = cipherText.length;
            int outPutSize = cipher.getOutputSize(len);
            System.out.println("Out Put Buffer Size in Decrypt= "+ outPutSize); // here output buffer coming is 165
              System.out.println("Decrypting Final");
              
            //byte[] cipherText1 = new byte[32];
            cipherText = cipher.doFinal(cipherText);
              System.out.println("Sending Cipher Text to Decrypt Method");
    
            return cipherText;
          }
    As mentioned here the output size in encryption and decryption is 160 and 165 respectively.

    Is anything else needed ?

    Regards,
    Ajay
  • 7. Re: How to decrypt entered value if Cipher outputsize is different.
    EJP Guru
    Currently Being Moderated
    System.arraycopy(parameterKeyBytes, 0, keyBytes, 0, Math.min(parameterKeyBytes.length, keyBytes.length));
    What's that for? You already have the bytes you got from the key. Just return those. Who said anything about truncating them to 16 bytes?
    {     public String encrypt(String plainText, String key)// throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{
    This method seems OK ...
    catch(Exception e){
    Except for that. Lose it. You have declared the method to throw several exceptions. Let it do so. Otherwise if something goes wrong you are letting the program keep running with garbage input. Don't do that.
    e.getMessage();
    This does exactly nothing. It is a complete waste of time, and catching the exception just to execute this code is worse than a waste of time: it is positively misleading.
    public static byte[] encrypt(byte[] plainText, byte[] key, byte [] initialVector) throws Exception,NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
    I'm not convinced you can use the key bytes as the IV, or that it's a good idea. Is that why you truncated the key bytes to 16? I wouldn't do this, I would use a hard coded IV.
    byte[] keyBytes = getKeyBytes(key);
    This seems all OK to here except that here you are truncating the key bytes again.
    byte[] decryptBytes = decrypt(cipheredBytes, keyBytes, keyBytes);
    And here you are using the key as the IV. Don't.
    catch (Exception e)
    {
    e.getMessage();
    }
    And here we have exactly the same rubbish as above. You've declared the method to throw several exceptions, yet here you are catching them all and calling a method that returns a string and then doing nothing with that string. Throw the try/catch away in both places.
    the output size in encryption and decryption is 160 and 165 respectively.
    I still don't understand why you think this is a problem, especially after you've been told otherwise. The ciphertext is 160 bytes long, the plaintext is 165 long. Why should these numbers be the same? It doesn't make any sense.

    You've also missed the statement in the Javadoc where it says "The actual output length of the next update or doFinal call may be smaller than the length returned by this method," which invalidates the entire issue anyway.

    At present it is entirely possible that you are throwing exceptions at both ends and never knowing about it. I would do the following:

    1. Don't truncate the key bytes.
    2. Define a hardcoded IV.
    3. Throw away all the try/catch rubbish at both ends.
  • 8. Re: How to decrypt entered value if Cipher outputsize is different.
    sabre150 Expert
    Currently Being Moderated
    >
    1. Don't truncate the key bytes.
    Last time I checked the AES key had to be exactly 16,24 or 32 bytes so may need to be truncated. I have bigger objections regarding the key; it should not be a String and should be read from a password protected Keystore.
    2. Define a hardcoded IV.
    I assume this means you would use a fixed IV; if not then ignore what follows.

    A fixed IV means that one can tell if two ciphertext are encryptions of the same cleartext which is normally undesirable. It is considered better to use a random IV and prefix the cipher text with the IV so that it can be used in the decryption process. Unfortunately this means that the ciphertext must increase in length. One can usually get away with less than the full 16 bytes of AES IV (padding it with a fixed value to make if of length 16 bytes) but I would still use 16 bytes if possible. Taken with using PKCS5 padding one ends up with between 17 and 32 bytes longer ciphertext than cleartext.
  • 9. Re: How to decrypt entered value if Cipher outputsize is different.
    Ajay Sharma Newbie
    Currently Being Moderated
    Hi.
    {quote:title=EJP wrote:}
    1. Don't truncate the key bytes.
    As per my knowledge AES algorithm supports 128 bit key. 16 bytes = 128 bit.

    If I don't do this its not performing Encryption or Decryption.

    I tested in normal class with main method I got runtime Exception
    Invalid AES key length
    Regards,
    Ajay

    Edited by: Ajay Sharma on Sep 14, 2012 10:10 AM
  • 10. Re: How to decrypt entered value if Cipher outputsize is different.
    EJP Guru
    Currently Being Moderated
    OK so ya got me on the key length and the IV. Still leaves the exception handling ;-)
  • 11. Re: How to decrypt entered value if Cipher outputsize is different.
    Ajay Sharma Newbie
    Currently Being Moderated
    Hi.


    :D I changed the exception handling part

    but I didn't understand yet why its not decrypting.

    My confusion is that if the same code is working in Java class with main method why its not working in Java Web Service class



    Regards,
    Ajay
  • 12. Re: How to decrypt entered value if Cipher outputsize is different.
    sabre150 Expert
    Currently Being Moderated
    Ajay Sharma wrote:

    but I didn't understand yet why its not decrypting.
    In what way? Is is throwing an exception or is it just giving the wrong result? If it is just giving the wrong result then in what way?
  • 13. Re: How to decrypt entered value if Cipher outputsize is different.
    EJP Guru
    Currently Being Moderated
    :D I changed the exception handling part
    With what effect?
    but I didn't understand yet why its not decrypting.
    Neither do I. Nor do I understand how you expect anybody to be able to help you when you don't provide any information.

    I am also still waiting to hear why SSL isn't a better solution for you.
  • 14. Re: How to decrypt entered value if Cipher outputsize is different.
    Ajay Sharma Newbie
    Currently Being Moderated
    Hi..

    No it is not throwing an exception and Its not showing any results.

    When I put SOP statements after every method call in my decrypt method, as follow
              System.out.println("Decrypting Final");
              cipherText = cipher.doFinal(cipherText);
              System.out.println("Sending Cipher Text to Decrypt Method");
    Its printing "Decrypting Final " on server console. But not the statement after cipher.doFinal method.

    I think it getting stuck at doFinal method. but I am not getting the reason behind it.


    Regards,
    Ajay
1 2 Previous Next

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points