mcrypt_create_iv

(PHP 4, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_create_iv从随机源创建初始向量

警告

此函数自 PHP 7.1.0 起弃用,并在 PHP 7.2.0 中移除

此函数可以使用如下替代:

说明

mcrypt_create_iv(int $size, int $source = MCRYPT_DEV_URANDOM): string

从随机源创建初始向量。

初始向量只是为了给加密算法提供一个可用的种子, 所以它不需要安全保护, 你甚至可以随同密文一起发布初始向量也不会对安全性带来影响。

参数

size

初始向量大小。

source

初始向量数据来源。可选值有: MCRYPT_RAND (系统随机数生成器), MCRYPT_DEV_RANDOM (从 /dev/random 文件读取数据) 和 MCRYPT_DEV_URANDOM (从 /dev/urandom 文件读取数据)。 在 Windows 平台,PHP 5.3.0 之前的版本中,仅支持 MCRYPT_RAND

请注意,在 PHP 5.6.0 之前的版本中, 此参数的默认值为 MCRYPT_DEV_RANDOM

注意: 需要注意的是,如果没有更多可用的用来产生随机数据的信息,那么 MCRYPT_DEV_RANDOM 可能进入阻塞状态。

返回值

返回初始向量。如果发生错误,则返回 false

示例

示例 #1 mcrypt_create_iv() 示例

<?php
$size
= mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB);
$iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
?>

参见

添加备注

用户贡献的备注 2 notes

up
44
Graham
10 years ago
In relation to all of the crypto "advice" seen here, my suggestion is that you ignore most of it. Some of it is good, some of it is bad, but most of it skips the critical issues.

I had hoped to write out a nice long explanation, but PHP's commenting system tells me my essay is too long. Instead I will say this:

You should use CBC, with a randomly chosen IV that is unique per key, and you should transmit that IV in the clear along with your ciphertext. You should also perform an authenticity check of that entire data blob, using something like HMAC-SHA256, with another independent key.

Here's the full-text of what I was going to write: http://pastebin.com/sN6buivY

If you're interested in this stuff, or just want more information, check out the Wikipedia articles around block cipher modes, block ciphers, HMAC, etc.

I also suggest reading Practical Cryptography by Bruce Schneier, as well as Cryptography Engineering by Niels Ferguson, both of which are very easy-to-digest books on practical cryptography.
up
16
Chris
18 years ago
>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!
To Top