-1

I am trying to create a function which can encrypt a string. I have the following code but I am getting an error.

$key = "testkey"; // This is the function that does the encryption. Treat it as a black box. Do not edit! function encrypt($str, $key){ $block = mcrypt_get_block_size('ISO-8859-1', 'ecb'); $pad = $block - (strlen($str) % $block); $str .= str_repeat(chr($pad), $pad); return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB)); } // call the encrypt function and send it the key and the data to encrypt. Store the returned data in the $dataopt variable. $dataopt = encrypt($rawstring, $key);

The error is "mcrypt_get_block_size(): Module initialization failed on line on line 41" which is $block = mcrypt_get_block_size('ISO-8859-1', 'ecb');

Any ideas?

deanhodges
  • 79
  • 1
  • 12

1 Answers1

0

You are passing 'ISO-8859-1' as the first parameter to mcrypt_get_block_size.

You probably meant to pass MCRYPT_RIJNDAEL_128 as the first parameter.

Please note that mcrypt has been deprecated so you should probably look into other solutions. Have a look at this question for some alternatives.

Community
  • 1
  • 1
Oz Solomon
  • 2,969
  • 23
  • 22
  • Hi Oz. Thanks for reply. I have replaced `ISO-8859-1` with MCRYPT_RIJNDAEL_128 but I get the error "Warning: mcrypt_encrypt(): Key of size 7 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported in" on line 44 which relates to return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB)); Thanks for your help – deanhodges Feb 21 '17 at 22:02
  • @deanhodges if the answer helped, please accept it. As I mentioned, I strongly suggest that you don't use `mcrypt` at all. Your error is that you need a binary key and you're passing in a string (see http://php.net/manual/en/function.mcrypt-encrypt.php). mcrypt is very low level and its easy to get things conceptually wrong **even if everything looks fine**. I don't know why you're specifically trying to encrypt strings but there a better solution than mcrypt out there for almost any need. – Oz Solomon Feb 21 '17 at 22:12