Question

I'm using an mcrypt function to encrypt a block of text using TripleDES. 90% of the time it works as it should and I can decrypt just fine. The other 10% though I just cannot decrypt it at all - as if I have the wrong key or the data is mangled.

The function is as follows:

function enc($text, $key, $iv) {
  $text_num = str_split($text, 8);
  $text_num = 8 - strlen($text_num[count($text_num)-1]);

  for ($i=0; $i < $text_num; $i++) {
    $text = $text . chr($text_num);
  }

  $cipher = mcrypt_module_open(MCRYPT_TRIPLEDES, '', 'cbc', '');
  mcrypt_generic_init($cipher, $key, $iv);
  $decrypted = mcrypt_generic($cipher, $text);
  mcrypt_generic_deinit($cipher);
  return base64_encode($decrypted);
}

They key & IV are the correct lengths (24/8 respectively) and never change. Like I said, it runs the exact same code on everything but only 10% fail in this way.

Is there anything I could be passing in $text that is causing this? Does it not like certain character sets? Or can this happen due to low memory/some other server condition?

Any help pinning this down would be much appreciated. Thanks!

Was it helpful?

Solution

(Copied from comment) 3DES has a 64 bit blocksize (8 bytes). You need to look at the exact size of the plaintext to check at it in terms of number of blocks. Look in the documentation for mention of padding, probably PKCS5 or possibly PKCS7. Is your "10%" failure actually 12.5% failure (1 in 8)? That would tend to point to something relating to blocking.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top