2

I am encrypting some data in my Android application, which is then sent to a PHP page for decryption and treatment.

The cipher being used is "AES/CBC/PKCS5Padding"

Everything works fine now (after alot of digging around for info). However, the resulting decrypted data has a number of new lines added to the end which do not exist in the original data sent from the application.

I am presuming that this is a side effect of PHP not supporting PKCS5Padding. I am uncomfortable assuming that the end will always have newlines or spaces appended to the string.

If I try to use the code proposed in the mcrypt docs, the encrypted buffer is emptied.

Is there a better workaround for unpadding ?


Edit : code added as per request

PHP

$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, "", MCRYPT_MODE_CBC, "");
if($cipher === false)
{
    trigger_error("AES compatible cipher missing", E_USER_WARNING);
    exit;
}
$InitResult = mcrypt_generic_init($cipher, $AesPassword, $AesIv);
if($InitResult !== 0)
{
    trigger_error("AES cipher init failed", E_USER_WARNING);
    exit;
}
// now do the decryption
$DataBlock = mdecrypt_generic($cipher, $EncryptedBlock);
// close down mcrypt
mcrypt_generic_deinit($cipher);
mcrypt_module_close($cipher);

Android/Java :

String strEncrypted = null;
Cipher cipher = null;
IvParameterSpec ivSpec = null;
byte[] btEncrypted = null;

try
{
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    ivSpec = new IvParameterSpec(m_btIV);

    cipher.init(Cipher.ENCRYPT_MODE, m_KeySpec, ivSpec);
    btEncrypted = cipher.doFinal(strData.getBytes(m_strCharSet));
    strEncrypted = Base64.encodeToString(btEncrypted, Base64.NO_PADDING | Base64.NO_WRAP);
}
catch(Exception e)
{
    e.printStackTrace();
}

return strEncrypted;

Note that the key and iv are calculated in Android and transmitted in the POST data to the server.

Does this help ?

Simon
  • 2,208
  • 4
  • 32
  • 47

1 Answers1

1

Unfortunately the Java SE providers do not support PHP padding. Bouncy Castle does not support this kind of padding either as Bouncy Castle always pads with at least 1 byte, even for zero padding.


So after a lot of tweaking, this is the best I can come up with:

/**
 * Pads data with zero valued bytes until the next block boundary is met.
 * Does not pad if the number of blocks is already on a boundary. This
 * method is not safe for binary data that may end with zero valued bytes as
 * they may be removed by the unpadding method.
 * If available, try and use PKCS#7 compatible padding instead.
 * 
 * @param data
 *            the binary data to pad, never null
 * @param blocksize
 *            the block size in bytes of the block cipher
 * @return the padded binary data as a copy
 * @throws NullPointerException
 *             if data is null
 */
public static byte[] phpPad(final byte[] data, final int blocksize) {
    if (data.length == 0) {
        return data;
    }

    final int blocks = (data.length - 1) / blocksize + 1;
    return Arrays.copyOf(data, blocks * blocksize);
}

/**
 * Unpads data removing zero valued bytes, removing up to blocksize - 1
 * bytes of padding. The input of the unpad method should consist of n times
 * the blocksize.
 * 
 * @param data
 *            the binary data to unpad, never null
 * @param blocksize
 *            the block size in bytes of the block cipher
 * @return the unpadded binary data as a copy
 * @throws NullPointerException
 *             if data is null
 * @throws IllegalArgumentException
 *             if the data is not n times the blocksize
 */
public static byte[] phpUnpad(final byte[] data, final int blocksize) {
    if (data.length % blocksize != 0) {
        throw new IllegalArgumentException(
                "Padded data should dividable by the block size");
    }

    if (data.length == 0) {
        return data.clone();
    }

    int padBytes = 0;
    for (; padBytes < blocksize; padBytes++) {
        if (data[data.length - padBytes - 1] != 0x00) {
            break;
        }
    }

    return Arrays.copyOf(data, data.length - padBytes);
}
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • Hi owlstead, thanks for your work on this. However, I am a bit confused here. The encrypted buffer is coming out of android java having requested PKCS#5 padding - are you saying that android java will not produce correct PKCS#5 padding ? Or, are you saying that it will be padded with null bytes? Hence your two PHP functions above ? – Simon May 26 '14 at 18:25
  • Ah, maybe I'm doing this the wrong way around, PKCS#5/7 padding is better, so using it in PHP is the better solution. I normally get questions where the PHP code cannot be changed... But in that case, [you cannot go wrong with Paũlo](http://stackoverflow.com/a/7324793/589259) – Maarten Bodewes May 26 '14 at 18:44