php openssl random pseudo bytes

openssl_random_pseudo_bytes

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_random_pseudo_bytes — Generate a pseudo-random string of bytes

Description

Generates a string of pseudo-random bytes, with the number of bytes determined by the length parameter.

Parameters

The length of the desired string of bytes. Must be a positive integer. PHP will try to cast this parameter to a non-null integer to use it.

If passed into the function, this will hold a bool value that determines if the algorithm used was «cryptographically strong», e.g., safe for usage with GPG, passwords, etc. true if it did, otherwise false

Return Values

Returns the generated string of bytes on success, or false on failure.

Changelog

Examples

Example #1 openssl_random_pseudo_bytes() example

The above example will output something similar to:

See Also

User Contributed Notes 11 notes

Here’s an example to show the distribution of random numbers as an image. Credit to Hayley Watson at the mt_rand page for the original comparison between rand and mt_rand.

rand is red, mt_rand is green and openssl_random_pseudo_bytes is blue.

NOTE: This is only a basic representation of the distribution of the data. Has nothing to do with the strength of the algorithms or their reliability.

( «Content-type: image/png» );
$sizex = 800 ;
$sizey = 800 ;

[Editor’s note: the bug has been fixed as of PHP 5.4.44, 5.5.28 and PHP 5.6.12]

Until PHP 5.6 openssl_random_pseudo_bytes() did NOT use a «cryptographically strong algorithm»!
See bug report https://bugs.php.net/bug.php?id=70014 and the corresponding source code at https://github.com/php/php-src/blob/php-5.6.10/ext/openssl/openssl.c#L5408

Another replacement for rand() using OpenSSL.

Note that a solution where the result is truncated using the modulo operator ( % ) is not cryptographically secure, as the generated numbers are not equally distributed, i.e. some numbers may occur more often than others.

A better solution than using the modulo operator is to drop the result if it is too large and generate a new one.

If you don’t have this function but you do have OpenSSL installed, you can always fake it:

FYI, openssl_random_pseudo_bytes() can be incredibly slow under Windows, to the point of being unusable. It frequently times out (>30 seconds execution time) on several Windows machines of mine.

Apparently, it’s a known problem with OpenSSL (not PHP specifically).

Getting an integer value from a given range with an even distribution:

This function I created to solve the problem of modulo results causing overlap of ranged results (which gave an uneven distribution).

What I mean for those not as familiar with the problem:

Using bytes for base 256 (base 16) and attempting to find a value in a range of values that may be for example 10-20 (a spread of 11) will not divide evenly, so values (using mod) will overlap and give more priority to some numbers than others.

Instead of calculating based on byte values, I used the byte values as keys to sort. This is very fast, and does not require large multiplications of data space that easily go over the value of Max Int.

Additionally: To make the user-supplied arguments not care about order I am using a handy swap function I found in the wild in conjunction with my function below.

function swap(&$a,&$b) < list($a,$b)=array($b,$a); >// swap 2 variables— no temp variable needed!

// function to get a random value within a given range of integers

//
// example getting values from 14 to 21:
//

//
// sample results from 14-21
//

-> result: 14
-> result: 18
-> result: 20
-> result: 15
-> result: 20
-> result: 16
-> result: 21
-> result: 15
-> result: 16
-> result: 17

Источник

Неожиданное поведение openssl_random_pseudo_bytes() приводящее к фатальной потере криптостойкости

Доброго времени суток всем.
php openssl random pseudo bytes. Смотреть фото php openssl random pseudo bytes. Смотреть картинку php openssl random pseudo bytes. Картинка про php openssl random pseudo bytes. Фото php openssl random pseudo bytes
Недавно в одном из проектов мы столкнулись со следующей проблемой — функция openssl_random_pseudo_bytes() выдавала дублирующиеся псевдослучайные последовательности!

И тем не менее — ошибки уникальности при вставке в базу сыпались пачками и лог подтверждал — 32-байтные последовательности генерировались повторно через разные интервалы, от суток до недели. Расследование заняло целый месяц. Сейчас я на 99% уверен, что причина найдена — но буду благодарен, если Хабражители подтвердят или опровергнут мои выводы.

Проблема усугубляется тем, что самые лучшие рекомендованные методы борьбы ( Call RAND_seed after a fork и Call RAND_poll after a fork) на ПХП неприменимы, так как эти функции OpenSSL попросту недоступны из ПХП.

К сожалению, мне не удалось найти в сети адекватных материалов по этой проблеме, за исключением уже приведенной статьи OpenSLL, но она не описывает конкретную связку Apache + PHP + OpenSSL. Зато статей настоятельно рекомендующих использовать openssl_random_pseudo_bytes() как криптостойкий ГСЧ — предостаточно.

В итоге — пришлось попросту отказаться от использования openssl_random_pseudo_bytes() и перейти на прямое чтение из /dev/urandom. Не самое блестящее решение — но достаточное в нашем случае.

Поскольку автор не является экспертом в области криптографии и мои выводы могут быть неверны / неполны, а проблема является более чем серьезной, учитывая распространенность рекомендаций по использованию openssl_random_pseudo_bytes(), то я обязательно изучу все комментарии специалистов и возможно исправлю / дополню (или удалю, если в корне не прав) статью. Также, если выводы подтвердятся, необходимо будет внести дополнения в документацию ПХП и предложения по добавлению RAND_seed/RAND_poll и / или их вызовы при старте скрипта в ПХП.

Важно! Apache должен работать в prefork режиме (MPM prefork). Версия ПХП с которой проблема проверялась — 5.5.x, но, предположительно, будет воспроизводиться в любой версии имеющей openssl_random_pseudo_bytes()

Источник

Generate a single use token in PHP: random_bytes or openssl_random_pseudo_bytes?

I need to generate a single-use token in PHP. There are two functions available that I can use for this that seem to do the same thing: random_bytes and openssl_random_pseudo_bytes. For example, using random_bytes :

and using openssl_random_pseudo_bytes :

openssl_random_pseudo_bytes is PHP 5.3 and up (so I assume it’s been around longer), and random_bytes is PHP 7. I’m using PHP 7 so I can use either.

So is there any major (or minor for that matter) difference between the two? If not, I’m tempted to go with random_bytes simply because it has an easier name ( = code that’s easier to read).

php openssl random pseudo bytes. Смотреть фото php openssl random pseudo bytes. Смотреть картинку php openssl random pseudo bytes. Картинка про php openssl random pseudo bytes. Фото php openssl random pseudo bytes

3 Answers 3

openssl_random_pseudo_bytes is part of the OpenSSL extension, which must be explicitly configured and included in the PHP compilation process and requires external dependencies.

random_bytes is new in PHP 7 as the native always-available PHP method to generate random bytes, which chooses its internal source of randomness depending on the platform it’s on.

The main reason for introducing random_bytes was that generating pseudo-random data was always a bit of a headache in PHP, requiring developers to be platform-aware and possibly using several different fallback methods depending on which extensions or system-level functions are available. This often led to bugs in individual implementations, which is particularly concerning in security-relevant code. random_bytes simplifies this by providing one function which is always available and uses the best possible source of randomness available. If you can target PHP 7+ exclusively, it should be your go-to method.

Источник

should i use urandom or openssl_random_pseudo_bytes?

I am developing a site in php 5.4 and i was wondering which is better to use to gen a random salt for password security?

or should i just go with:

2 Answers 2

In practice, there is almost certainly no difference.

Both openssl_random_pseudo_bytes and /dev/urandom provide a cryptographically secure source of pseudorandom bytes. Neither is guaranteed to be truly random, but in practice, both are expected to be indistinguishable from true randomness by any known or foreseeable techniques.

Kmkaplan is technically correct in noting that /dev/urandom could return theoretically predictable output under certain conditions, as noted in man unrandom :

«A read from the /dev/urandom device will not block waiting for more entropy. As a result, if there is not sufficient entropy in the entropy pool, the returned values are theoretically vulnerable to a cryptographic attack on the algorithms used by the driver. Knowledge of how to do this is not available in the current unclassified literature, but it is theoretically possible that such an attack may exist. If this is a concern in your application, use /dev/random instead.»

However, the same is actually true of openssl_random_pseudo_bytes (which calls the OpenSSL function RAND_pseudo_bytes internally), as noted in the OpenSSL documentation:

» RAND_pseudo_bytes() puts num pseudo-random bytes into buf. Pseudo-random byte sequences generated by RAND_pseudo_bytes() will be unique if they are of sufficient length, but are not necessarily unpredictable. They can be used for non-cryptographic purposes and for certain purposes in cryptographic protocols, but usually not for key generation etc.»

Neither of these warnings should actually scare you from using these methods — the weaknesses they describe are only theoretical, except possibly under certain contrived circumstances (such as on a diskless embedded device with no hardware RNG immediately after boot-up), and should not be of practical concern in situations where PHP is normally deployed.

The upshot is, neither of these random number generation methods is going to be the weakest link in your cryptosystem, so you can safely choose either one. If you’re feeling paranoid, you could even use both.

Ps. One advantage of openssl_random_pseudo_bytes is that it works on Windows, too. On the other hand, /dev/urandom is available on Unix even if the OpenSSL PHP extension is not installed. Thus, for maximum portability, you should indeed implement support for both.

Also, always check that you indeed received as many bytes as you expected; for example, the /dev/urandom based code in your question above could silently return an empty string on systems like Windows where /dev/urandom does not exist.

Источник

Что делает openssl_random_pseudo_bytes & quot; криптографически безопасным & quot ;?

Мне всегда говорили, что я должен использовать openssl_random_pseudo_bytes при вводе паролей соль.

Решение

Свойства также перечислены в таблице ниже:

php openssl random pseudo bytes. Смотреть фото php openssl random pseudo bytes. Смотреть картинку php openssl random pseudo bytes. Картинка про php openssl random pseudo bytes. Фото php openssl random pseudo bytes

За rand это указано в mt_rand :

Многие генераторы случайных чисел старых библиотек имеют сомнительные или неизвестные характеристики и работают медленно.

Таким образом, для rand вам нужно будет взглянуть на свою библиотеку libc, чтобы выяснить, какой случайный код фактически используется. На сайте Mersenne Twister заявлено, что в настоящее время он должен иметь сопоставимую скорость, но его характеристики зависят от системы. В нем также не указано, как он будет посеян, то есть вы можете использовать его для игры или чего-то подобного, но не для чего-то еще.

mt_rand

Mersenne Twister — это хорошо известный алгоритм, который выдает довольно хорошо распределенные случайные числа. Он имеет очень длительный период, что означает, что пройдет много времени, прежде чем будет найдено предыдущее состояние (если это происходит, оно остается в цикле, размер цикла называется периодом). MT не является безопасным, потому что можно восстановить его безопасное состояние с учетом достаточного количества данных. Это означает, что если вы сначала сгенерируете ключ, а затем используете алгоритм для чего-то другого, то злоумышленник может воссоздать ключ с учетом достаточного количества вывода. Кроме того, небезопасное начальное число как системное время используется при создании.

openssl_random_pseudo_bytes

Генератор случайных чисел в OpenSSL обычно криптографически безопасен (см. Примечание ниже); это означает, что невозможно пересчитать внутреннее состояние с учетом выходной мощности генератора.

Генератор псевдослучайных чисел в OpenSSL построен с использованием хеш-функции, в настоящее время MD5, которая должна быть безопасной для генерации случайных чисел. Он хорошо распределен и — как алгоритм MT — имеет большой период. OpenSSL, rand намного медленнее, чем MT, но все равно должен набрать довольно хорошую скорость.

Он имеет преимущество перед генераторами случайных чисел в ОС, так как не требует дополнительных потоков или системных вызовов. OpenSSL использует генератор случайных чисел операционной системы (+ возможные другие источники) для создания начального начального числа. Генераторы случайных чисел в ОС обычно являются наилучшими из возможных генераторов случайных чисел, поскольку ОС имеет доступ к источникам энтропии, которые не доступны напрямую библиотекам и приложениям.

Предупреждение: в вики OpenSSL указано, что:

Что отражается функцией PHP:

Если оно передается в функцию, оно будет содержать логическое значение, которое определяет, был ли используемый алгоритм «криптографически стойким», например, безопасным для использования с GPG, паролями и т. Д. TRUE если это так, иначе FALSE

Это означает, что он все еще может быть небезопасным, например, долгосрочные ключи.

Предупреждение № 2: дополнительная информация показывает, что PRNG в OpenSSL не всегда может быть безопасным независимо от возвращаемого значения. Поэтому следует проявлять дополнительную осторожность перед выбором OpenSSL.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *