1

I'm working on a android project in which I have to decrypt string from a file in PHP server, encryption was done using PHP.(AES 128 algorithm)

Encryption Code:

 function aes128Encrypt($key, $data) {
      $key = md5($key);
      return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16));
    }

My code for getting string from URL:

String myUri = "http://www.example.com/lib2.php";
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(myUri);

HttpResponse response = httpClient.execute(get);

String bodyHtml = "";
String xmlFile = "";
bodyHtml = EntityUtils.toString(response.getEntity());
System.out.println(bodyHtml);
xmlFile = decrypt(bodyHtml);
System.out.println(xmlFile);

decrypt() method:

public static String decrypt(String encData) throws Exception
    {
        Key key = generateKey();

        Cipher c = Cipher.getInstance(algo + "/CBC/PKCS7Padding");

        //Cipher c = Cipher.getInstance(algo);

        IvParameterSpec ivSpec = new IvParameterSpec(ivbytes);

        c.init(Cipher.DECRYPT_MODE, key , ivSpec);

        //byte[] decValue = Base64.decode(encData , Base64.NO_PADDING);

        //byte[] decFin = Base64.decode(decValue, Base64.NO_PADDING);

        //byte[] decFinal = c.doFinal(decValue);

        byte[] decFinal = c.doFinal(encData.getBytes());

        String getAns = new String(decFinal, "UTF8");

        return getAns;
    }

In generateKey():

public static Key generateKey()
    {

        try {
            MessageDigest digest = java.security.MessageDigest
                    .getInstance("MD5");

            digest.update(myChar.getBytes());

            key1 = digest.digest();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }



        Key key = new SecretKeySpec(key1,algo);     
        return key;
    }
}

The Logcat shows below exception:

javax.crypto.IllegalBlockSizeException: last block incomplete in decryption

at the line c.doFinal()

The Codes I'v commented out are also the codes I'v used to check. What is wrong with this code?. Any help will be appreciated.

3
  • 2
    Please do not use MD5 for key strengthening. If the key is already cryptographically strong you are all but wasting processor cycles hashing it with md5. If the key is not cryptographically strong please use a proper algorithm like Scrypt, Bcrypt or PBKDF#2 to facilitate key strengthening.
    – initramfs
    Dec 15, 2013 at 5:02
  • @CPUTerminator Sure, but that won't solve this issue, will that? And also I don't have permission to change any code in PHP. So is there any way to solve this? Dec 15, 2013 at 12:59
  • No it won't solve your issue. But the solution posted by Max Power will. If no padding mechanism is specified, by default php pads the message with \0 (I think) if the message isn't a multiple of the block size. Thus using AES/CBC/NoPadding should yield a message that is correct but may have additional spaces at the end. Since the message has been pre-padded by php to a appropriate size.
    – initramfs
    Dec 15, 2013 at 14:08

3 Answers 3

2

Your chiper is expecting padding "/CBC/PKCS7Padding". This has nothing to do with encoding of messages (BASE64). Either change expected chipher on java side or encrypt with padding on php side.

Chipers are specified algorithm/mode/padding or algortihm, see http://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html for details.

Your are specifying a chiper with padding but actually do zero padding on php side,

excerpt from http://www.php.net/manual/de/function.mcrypt-encrypt.php:

# creates a cipher text compatible with AES (Rijndael block size = 128)
# to keep the text confidential 
# only suitable for encoded input that never ends with value 00h
# (because of default zero padding)
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
                             $plaintext, MCRYPT_MODE_CBC, $iv);
4
  • I can't change anything on PHP side, What should I change in java code , Padding? since I'v used the same AES algorithm , CBC mode used in PHP. Dec 13, 2013 at 9:01
  • 1
    Please try with "AES/CBC/NoPadding"
    – Max Power
    Dec 13, 2013 at 9:32
  • 1
    Thank you.I'v tried using NoPadding but it gives javax.crypto.IllegalBlockSizeException: error:0606508A:digital envelope routines:EVP_DecryptFinal_ex:data not multiple of block length. That means anything to do with the data read? Dec 13, 2013 at 10:00
  • @NitinMisra Yes, Please check the answer I have accepted. Jul 9, 2014 at 9:56
1

The problem probably is the way you treat the value from the PHP server as a Java String. The PHP mcrypt_encrypt function returns a binary string, where each byte can have any value. PHP mcrypt_encrypt does not use any character encoding. So using EntityUtils.toString() is already an error - and using String.getBytes() without specifying the encoding generally is as well.

You just need to use either getContent() or writeTo(OutputStream outstream) to get the the binary ciphertext. If you opt for the first option, you can wrap a CipherInputStream around it. Initialize it with the "AES/CBC/NoPadding" cipher and you can directly decrypt the plain text string. Beware that you may have to trim a certain number of 00 valued bytes from the result to get to the plaintext.

5
  • And also what should I do to trim and get the exact string?, I'm getting it like a corrupted one now. Dec 16, 2013 at 11:09
  • A corrupted plaintext indicates that something is still a mismatch between the encryption/decryption or encoding/decoding. Note that without padding, decryption will only fail if the stream does not contain a full number of blocks. If the key or ciphertext has been altered, it will simply return garbage... Trimming is only required for 00 bytes at the end, as indicated. Dec 16, 2013 at 14:10
  • But the plaintext not fully corrupted it's the same text before encryption, but its not in order, starts printing from beginning of the text ends and then again prints from beginning. I'v used like this byte[] encData = new byte[1600]; String add = ""; while((dummy = cis.read(encData)) != -1) { System.out.println(new String(encData , "UTF-8").trim()); add = add + (new String(encData , "UTF-8").trim()); } And I can't store the whole plain text in to a string , it only stores a part. Dec 17, 2013 at 5:42
  • Have a look at this: stackoverflow.com/questions/20628307/… Dec 17, 2013 at 7:27
  • @KarthikSivam looks like you already have answered your question there. There is no need to trim() each string by the way, you only need to remove (or: not decode) the last bytes valued 00 of the entire decrypted plaintext. Calling trim() for each block would remove whitespace from your plaintext (including spaces and such). Dec 17, 2013 at 18:59
0

I solved my problem by avoiding reuse of cipher. each time i init it again. just initing might be enough.

 try {
            SecretKeyFactory factory = SecretKeyFactory
                    .getInstance(SECRET_KEY_ALGORITHM);
            KeySpec spec = new PBEKeySpec(ps, salt, ITERATIONS, KEY_LENGTH);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKey secret = new SecretKeySpec(tmp.getEncoded(), ALGORITHM);

            // Build encryptor and get IV
            ecipher = Cipher.getInstance(TRANSFORMATION);
            ecipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(iv));

            // Build decryptor
            dcipher = Cipher.getInstance(TRANSFORMATION);
            dcipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
        } catch (Exception e) {
            e.printStackTrace();
        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.