Today's Question:  What's your opinion about Alibaba mooncake incident?        GIVE A SHOUT

Technical Article => Web =>  PHP

One reason why mcrypt responds slowly

  Peter      2012-09-27 12:03:16      5,278    4    0

This morning one colleague came over and talked about one script which used mcrypt responded very slowly, the server configurations are fine. Don't know the reason.

Here is one script which reproduces the issue:

  1. <?php
  2. $dmcryptText = "dummy";
  3. $key = "foobar";
  4. $size = mcrypt_get_iv_size(MCRYPT_BLOWFISH,MCRYPT_MODE_ECB);
  5.  
  6. $iv = mcrypt_create_iv($size); //Take care
  7.  
  8. $m = mcrypt_ecb(MCRYPT_BLOWFISH, $key, $dmcryptText, MCRYPT_DECRYPT, $iv);
  9. var_dump($m);

When 20 requests of this script are sent to the server in parallel, we can find the response time of Apache server increases rapidly.

The reason for the slowness is illustrated below.

If you don't specify argument for mcrypt_create_iv(), it will use /dev/random(on Linux) by default as a random number generator. The problem of /dev/random is that its random pool depends on the system interrupts, when there is not enough system interrupts, it cannot generate enough random numbers, then the process tries to get the random numbers will wait and hang. Let's look at a simple example.

$ dd if=/dev/random bs=1024k count=1

When your system is busy, you will find the output speed is very slow, sometimes there will be pause.

The solution is using /dev/urandom instead of /dev/random, /dev/urandom is also a random number generator, but it doesn't depends on system interrupts.

  1. <?php
  2. $dmcryptText = "dummy";
  3. $key = "foobar";
  4. $size = mcrypt_get_iv_size(MCRYPT_BLOWFISH,MCRYPT_MODE_ECB);
  5.  
  6. $iv = mcrypt_create_iv($size, MCRYPT_DEV_URANDOM); //Take care
  7.  
  8. $m = mcrypt_ecb(MCRYPT_BLOWFISH, $key, $dmcryptText, MCRYPT_DECRYPT, $iv);
  9. var_dump($m);

The reason why using /dev/random as default is that /dev/urandom is predictable in theory, so generally /dev/random is safer than /dev/urandom. Check : /dev/random

Author : Laruence Source : http://www.laruence.com/2012/09/24/2810.html

SOLUTION SLOW MCRYPT RESPONSE

  SAVE AS PDF   MARK AS READ   MARK AS IMPORTANT

Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious

  RELATED


  4 COMMENTS


Anonymous [Reply]@ 2016-04-05 02:14:58

Thanks it worked for me :)

Ke Pi [Reply]@ 2016-04-05 04:25:24

Glad to hear about this

Anonymous [Reply]@ 2016-06-23 04:24:14

After 2 nights of banging my head against the wall, this solved my problem, thank you !

Ke Pi [Reply]@ 2016-06-23 08:45:41

Glad to hear about this


  WRITE ARTICLE

Multithreading program written by newbie

By sonic0002