Bronek
Bronek

Reputation: 11235

mcrypt_decrypt - strange padding (not default, not with null)

I'm trying to use symmetric decryption with code as follow:

$encrypted = base64_decode($encryptedBase64String);
$returnText = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, key, $encrypted, MCRYPT_MODE_CBC, iv);

And I meet strange result (as nobody questioned). I don't know why method mcrypt_decrypt returns decrypted text with padding fulfilled with byte values which equals number of padded chars. According to the php manual the method should pad its return with zero values bytes.

To clarify it I have placed two examples below:

[Above call of mcrypt_decrypt pads return string to length of 32]

example 1

plainText = 'text'

length of 'text' is 4, so size of padding is 28 chars (32 - 4)

So I receive returnText as:

{\116\101\120\116\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28\28}

example 2

'12345678901234567890'

length = 20

{\49\50\51\52\53\54\55\56\57\48\49\50\51\52\53\54\55\56\57\48\12\12\12\12\12\12\12\12\12\12\12\12}

What can I do to change it? I have problem with removing padding with method rtrim("\0") since padding is not by null.

Upvotes: 3

Views: 2805

Answers (1)

gen_Eric
gen_Eric

Reputation: 227240

If the string to be encrypted is not the right length, mcrypt_encrypt will pad it with \0s. Whoever encrypted the string you are decrypting added their own padding first, so PHP didn't have to pad it. This type of padding is called PKCS7 padding.

To remove it you can try something like this (stolen from here):

$strPad = ord($returnText[strlen($returnText)-1]);
$returnText = substr($returnText, 0, -$strPad);

Upvotes: 9

Related Questions