Mcrypt 函数
在线手册:中文  英文

mcrypt_create_iv

(PHP 4, PHP 5)

mcrypt_create_ivCreates an initialization vector (IV) from a random source

说明

string mcrypt_create_iv ( int $size [, int $source = MCRYPT_DEV_RANDOM ] )

Creates an initialization vector (IV) from a random source.

The IV is only meant to give an alternative seed to the encryption routines. This IV does not need to be secret at all, though it can be desirable. You even can send it along with your ciphertext without losing security.

参数

size

The size of the IV.

source

The source of the IV. The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom). Prior to 5.3.0, MCRYPT_RAND was the only one supported on Windows.

返回值

Returns the initialization vector, or FALSE on error.

更新日志

版本 说明
5.3.0 MCRYPT_DEV_RANDOM and MCRYPT_DEV_URANDOM became available on Windows platforms.
5.3.0 It is no longer required to call srand() first. This is now done automatically.

范例

Example #1 mcrypt_create_iv() Example

<?php
    $size 
mcrypt_get_iv_size(MCRYPT_CAST_256MCRYPT_MODE_CFB);
    
$iv mcrypt_create_iv($sizeMCRYPT_DEV_RANDOM);
?>

参见


Mcrypt 函数
在线手册:中文  英文

用户评论:

nils at nm dot cx (2012-06-19 12:26:45)

If you use /dev/random you need a well filled entropy pool or the application will block until enough good entropy comes available

hans at llis dot nl (2012-04-29 10:01:14)

This does NOT generate randomly distributed IV's on all systems and therefore poses a big security risk. Using a script (based on the one that Alex Khimch's posted on the rand() page) one can easily check this:

<?php

$td 
mcrypt_module_open (MCRYPT_RIJNDAEL_256""MCRYPT_MODE_CBC"");
$iv mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_DEV_RANDOM);

// header("Content-type: image/png");
$img imagecreatetruecolor(255,255);

$ink imagecolorallocate($img,255,255,255);
for(
$i=0;$i<255;$i++) {
  for(
$j=0;$j<255;$j++) {
  
$twobytes substr ($iv02);
  
$iv substr ($iv2);
  if (!
strlen ($iv)) $iv mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND);

  
imagesetpixel($imgord($twobytes[0]), ord($twobytes[1]), $ink);
  }
}

imagepng($img);
imagedestroy($img);

?>

The resulting image should show random noise, but on the windows systems I tested (running PHP 5.3.x) it showed very distinct patterns.

Ori Peleg (2009-03-17 01:01:35)

If mcrypt_create_iv takes too long, try replacing MCRYPT_DEV_RANDOM with MCRYPT_DEV_URANDOM.
Secure random (/dev/random) isn't needed for the IV.

Matthew (2008-09-25 19:09:49)

I encrypt a few items on a page in a project i am working on and I have found the IV create function to introduce huge delays in rendering the page too (I noticed someone else here had this problem).
It's quite common for a 4 second render time for what should be a snappy site. I would recommend that if speed is essential that an alternative method be used to create your IV (such as the one below if you feel it secure enough).
After using an alternative IV creation method my page went from a 4 second render to a 0.01 second render time.

(2006-12-30 03:37:00)

Chris is right. I think that the person to whom he was responding was mixing up initialization vectors and salts that you would use when MD5 hashing passwords to prevent dictionary attacks. In that case they do need to be random to thwart the dictionary attack most effectively, although they don't need to be secret (which is a moot point since every salt is different).

Chris (2006-11-05 15:07:09)

>First, the IV should be random and variable. The whole >point of it is to ensure that the same plaintext does not >encrypt to the same ciphertext every time. You most >certainly do lose security if the IV is constant or public.
Wrong, Wrong WRONG! The initialization vector is ALLOWED to be PUBLIC! It is generally sent along with the ciphertext, UNENCRYPTED.
>The ciphertext should be E(IV | plaintext, key)
Wrong again! The initialization vector is NOT prepended to the plaintext before encryption. The IV is used to seed the feedback system! (which is why you don't need one in ECB mode - there is no feedback)
>Second, the IV should not be part of the decryption >parameters at all. You should be able to decrypt the cipher >text, throw away the initial vector at the front w/o even >reading it, and have your plaintext:
Nope. You need to seed the feedback mechanism during decryption to the SAME state as it was seeded during encryption. This means using the SAME IV!

kkaiser at dataresolutions dot com (2006-07-12 06:04:59)

Clarification: I meant to type MCRYPT_DEV_RANDOM, MCRYPT_DEV_URANDOM and MCRYPT_RAND in the previous note, instead of DEV_RANDOM, DEV_URANDOM and DEV_RAND. :)

kkaiser at dataresolutions dot com (2006-07-11 13:26:49)

After profiling a rather large, dynamic website I maintain to determine the cause of intermittent freezing in execution, I found that calls to mcrypt_create_iv() using DEV_RANDOM as the source consistently halted execution for anywhere from 0.2 to ~12 seconds per call, ironically at random. I'm making the assumption that the halts were caused by insufficient random input being currently available in /dev/random due to its intended function to block until enough random input is provided back to the device. I've found it to be sufficient for my needs to use a modified version of the alt_mcrypt_create_iv() function found below.
Although untested, I assume using DEV_URANDOM or a combination of DEV_RAND with srand() would've solved the problem as well; I found out after the fact that /dev/urandom's intended function is to seamlessly provide cryptographically secure output from the random number generator when the /dev/urandom buffer was empty, and DEV_RAND would simply use the same rand() function as alt_mcrypt_create_iv().
-Kevin Kaiser

Anonymous (2005-10-17 09:01:21)

At:
edwardzyang at thewritingpot dot com
19-Jul-2005 10:06
This is because of the fact, that (like described in the manual above) this function does NOT reseed the random number generator, in contrary to rand(). Use srand() like suggested above to get correct IVs.

(2005-09-04 11:12:17)

Correction to the last comment, the second parameter of rtrim() uses double quotes, not single quotes.
So the corrected code is as follows:
$retval = rtrim($retval, "\0"); // trim ONLY the nulls at the END
;)

edwardzyang at thewritingpot dot com (2005-07-19 13:06:41)

For some reason, on my Windows installation, MCRYPT_RAND doesn't work at all: it always gives the same IV. This is a huge problem, especially for OFB and CTR, where using the same IV destroys security.

Fortunantely, it's easy to emulate the IV function using other random generators that do indeed work (such as rand() ). Here's an example:

<?php

function alt_mcrypt_create_iv ($size) {
    
$iv '';
    for(
$i 0$i $size$i++) {
        
$iv .= chr(rand(0,255));
    }
    return 
$iv;
}

?>

Note that this doesn't make it "more random" in any way, it just let's you use your own favorite random function to create randomness than the quirky mcrypt_create_iv.

tim at indigopixel dot com (2004-03-17 16:32:11)

From http://www.ciphersbyritter.com/GLOSSARY.HTM#IV (linked to above):
"While it is often said that IV values need only be random-like or unpredictable, and need not be confidential, in the case of CBC mode, that advice can lead to man-in-the-middle attacks on the first plaintext block. If a MITM opponent knows the usual content of the first block, they can change the IV to manipulate that block (and only that block) to deliver a different address, or different dollar amounts, or different commands, or whatever. And while the conventional advice is to use a MAC at a higher level to detect changed plaintext, that is not always desirable or properly executed. But the CBC first-block problem is easily solved at the CBC level simply by enciphering the IV and otherwise keeping it confidential, and that can be reasonable even when a MAC will be used later."

robert at peakepro dot com (2004-03-03 12:25:20)

It is important to note that all cipher modes except ecb require the same IV to be used in decryption as was used in encryption. 

You need to pass the key *and* the IV to your decrypt function. Initializing a new IV in the decrypt routine will not work.

Since, "you even can send [the IV] along with your ciphertext without  loosing security," a nice way to handle this is to prepend your IV to your ciphertext. Since the IV is fixed-width, you can then easily recover the IV and original ciphertext using mcrypt_get_iv_size() and substr().

Here is an example:

<?PHP
function my_encrypt($string,$key) {
   
srand((double) microtime() * 1000000); //for sake of MCRYPT_RAND
   
$key md5($key); //to improve variance
  /* Open module, and create IV */
  
$td mcrypt_module_open('des''','cfb''');
  
$key substr($key0mcrypt_enc_get_key_size($td));
  
$iv_size mcrypt_enc_get_iv_size($td);
  
$iv mcrypt_create_iv($iv_sizeMCRYPT_RAND);
  
/* Initialize encryption handle */
   
if (mcrypt_generic_init($td$key$iv) != -1) {

      
/* Encrypt data */
      
$c_t mcrypt_generic($td$string);
      
mcrypt_generic_deinit($td);
      
mcrypt_module_close($td);
       
$c_t $iv.$c_t;
       return 
$c_t;
   } 
//end if
}

function 
my_decrypt($string,$key) {
   
$key md5($key); //to improve variance
  /* Open module, and create IV */
  
$td mcrypt_module_open('des''','cfb''');
  
$key substr($key0mcrypt_enc_get_key_size($td));
  
$iv_size mcrypt_enc_get_iv_size($td);
  
$iv substr($string,0,$iv_size);
  
$string substr($string,$iv_size);
  
/* Initialize encryption handle */
   
if (mcrypt_generic_init($td$key$iv) != -1) {

      
/* Encrypt data */
      
$c_t mdecrypt_generic($td$string);
      
mcrypt_generic_deinit($td);
      
mcrypt_module_close($td);
       return 
$c_t;
   } 
//end if
}
// to test:
//print my_decrypt(my_encrypt("Hello, world.","foo"),"foo");
?>

fandelem at hotmail dot com (2002-03-06 15:59:37)

note: if you are experiencing a problem about complaining that the second parameter has to be a 'long' and you are giving a 'string' (for me, it was using MCRYPT_URANDOM) you might want to try MCRYPT_DEV_URANDOM :)

易百教程