PKCS7 encoded AES 256 has half ECB and half CBC

Im trying to decode data in php returned from server: I know the data is AES 256 decoded and has PKCS7 padding but cannot determine which blocking mode it is using

here is my php function:

public function decode($data)
{
    //AES decode
    $iv = mcrypt_create_iv(GEServerConnection::FBENCRYPT_BLOCK_SIZE, MCRYPT_RAND);
    $data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->cryptKey, base64_decode($data), MCRYPT_MODE_ECB, $iv);

    //return $data;
    $len = strlen($data);
    $pad = ord($data[$len - 1]);

    return substr($data, 0, - $pad);
}

      

and an example of encoded data

3KD+zb/2u5gGEWvOy0Q0nSQE9pbQZmg27iN6WLiO/Af9YjN8MhHOb8TMa5uETaab

      

when i decode with ECB (MCRYPT_MODE_ECB) it only decodes the beginning of the data and the rest is unreadable

"Please input yo  ޸̓  g|  *P Te     R B

      

and when decoding with CBC mode (MCRYPT_MODE_CBC) it started unreadable

  0 =v      .3ur username and password again"

      

the result should be (what I get on mac with CommonCryptor in objective-c):

"Please input your username and password again"

      

does anyone know what is wrong or how to decode it correctly?

+3


source to share


1 answer


Please see the Wikipedia article . See how ECB and CBC stands for. If ECB were used in mode, you would decode all text correctly. It seems that the cipher used CBC because it uses the previous encryption text + current encryption text + decryption to get the original text. This is why you decoded the second block correctly.

Now why is the first block decoded incorrectly? This is because you need to provide the correct initialization vector. This should be the same as for encryption. We are lucky that we know that ECB decoded the first block, because ECB does not use an initialization vector.



The answer is simple: use CBC with a zero initialization vector (all bytes are zero), because now your random IV has changed the first block to the wrong output.

+5


source







All Articles