Raihan Al-maMun Raihan Al-maMun - 3 years ago 77
PHP Question

3DES PHP decrypts same result even if a char is added at the end

So i am using this class to encrypt or to decrypt data:

class CryptData
{
private $hash;
function __construct($hash) {
$key = md5($hash, true);
$key .= substr($key, 0, 8);
$this->hash = $key;
}
public function Encrypt($data)
{
$encData = openssl_encrypt($data, 'DES-EDE3', $this->hash, OPENSSL_RAW_DATA);
return base64_encode($encData);
}
public function Decrypt($data)
{
$data = base64_decode($data);
return openssl_decrypt($data, 'DES-EDE3', $this->hash, OPENSSL_RAW_DATA);
}
}


and it works fine but for example, if i use:

hash = 12345
text = 1234567891234567


and encrypt it then it results


decData = LQ1zff+UiAAs6GXEgA5x6beMPOubhpcA


Now if i try to decrypt this data back to plain text, then it gives me correct result but even if i add any char at the end of the decData like


decData = LQ1zff+UiAAs6GXEgA5x6beMPOubhpcAa


Surprisingly it gives correct plain text as well..!!
What i have noticed after few more test, decData with no '=' at the end, if i add a char then it will decrypt to text without error.
for example, if i try

hash = 12345
text = 12345


then it will result


decData = CQm/ZBYSrrs=


now if i decrypt this adding a char at the end then it will be an error.

so to sum up all, when i try to encrypt a text of length = 16 or more then there's no '=' in decrypted data. I don't have any problem with that but if I try to decrypt the decrypted data adding any char at the end, it gives me correct text back.

Why is this possible and is there any security issue with this problem to my data?

Answer Source

Base64 is used for encoding binary data into text where each Base64 character represents 6 bits. Each 3 bytes (24 bits) of input gives 4 Base64 characters. In the case where the input length is not a multi-plum of 3 the last block of Base64 is padded with one or two '='

Base64 encoded data needs to be in block of 4 Base64 characters to be valid Base64. It seems that php's base64_decoder(..) just ignores your last invalid Base64 char. You can see this with the following code:

echo strlen(base64_decode("LQ1zff+UiAAs6GXEgA5x6beMPOubhpcA"));
echo "\n";
echo strlen(base64_decode("LQ1zff+UiAAs6GXEgA5x6beMPOubhpcAa"));

Giving:

24
24
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download