php generate random string
Случайность в PHP7 – Повезет ли мне?
В этой статье мы проанализируем проблемы, относящиеся к генерации случайных чисел, используемых в криптографии. PHP5 не обеспечивает простой механизм генерации криптостойких случайных чисел, в то время как PHP7 решает эту проблему путем введения CSPRNG-функций.
Что такое CSPRNG?
Цитируя википедию, криптографически стойкий генератор псевдослучайных чисел (англ. Cryptographically secure pseudorandom number generator, CSPRNG) — это генератор псевдослучайных чисел с определёнными свойствами, позволяющими использовать его в криптографии.
CSPRNG в PHP7
random_int возвращает целое число в заданном диапазоне:
За кадром
Простой тест
Хорошая система генерации случайных чисел определяется «качеством» генераций. Чтобы его проверить часто используется набор статистических тестов, позволяющих, не вникая в сложную тему статистики, сравнить известное эталонное поведение с результатом генератора и помочь в оценке его качества.
График будет выглядеть так (чем ближе к нулю, тем лучше):
А что насчет PHP5?
Если вы хотите начать использовать хороший генератор случайных чисел и в то же время пока еще не готовы к переходу на PHP7, вы можете использовать библитеку random_compat от Paragon Initiative Enterprises. Она позволяет использовать random_bytes() и random_int() в PHP 5.х проектах.
Библиотеку можно установить через Composer:
Дополнительную информацию о том почему используется именно этот порядок вы можете прочитать в документации.
Пример генерации пароля с использованием библиотеки:
Краткий итог
Вы всегда должны применять криптографически стойкие генераторы псевдослучайных чисел, и random_compat является хорошим решением для этого.
Generating Random String Using PHP
Generate a random, unique, alpha-numeric string using PHP.
Program:
APPROACH 2: Using Hashing Functions
PHP has a few functions like md5(), sha1() and hash(), that can be used to hash a string based on certain algorithms like “sha1”, “sha256”, “md5” etc. All these function takes a string as an argument and output an Alpha-Numeric hashed string.
To learn more about these functions click here.
Program 1:
Program 2:
Program 3:
NOTE: All the above functions are hashing functions, hence the length of the string generated will always depend on the algorithm used, but for an algorithm it will always remain constant. So if you want to generate string of a fixed length, you can either truncate the generated string or concatenate with another string, based on the requirement.
Approach 3:Using uniqid() function.
The uniqid( ) function in PHP is an inbuilt function which is used to generate a unique ID based on the current time in microseconds (micro time). By default, it returns a 13 character long unique string.
Program:
NOTE: All the above approaches are built on rand() and uniqid() functions. These functions are not cryptographically secure random generators. So it is advised that if the degree of randomness affect the security of an application, these methods should be avoided.
Approach 4: Using random_bytes() function. (Cryptographically Secure)
The random_bytes() function generates cryptographically secure pseudo-random bytes, which can later be converted to hexadecimal format using bin2hex() function.
Program:
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Random String Generator (PHP)
I am trying write a PHP function that returns a random string of a given length. I wrote this:
The above function generates a random string, but the length of the string is not constant, ie: one time it is 30 characters, the other is 60 (obviously I call it with the same length as input every time). I’ve searched other examples of random string generators, but they all use a base string to pick letters. I am wondering why this method is not working properly.
3 Answers 3
Educated guess: you attempt to display your plain text string as HTML. The browser, after being told it’s HTML, handles it as such. As soon as a character is generated, the following characters are rendered as an (unknown) HTML tag and are not displayed as HTML standards mandate.
This is the conclusion i reached after testing it a while : Your functions works correctly. It depends on what you do with the randomly generated string. If you are simply echo-ing it, then it might generate somthing like which will be treated like a tag. Try eliminating certain characters from being concatenated to the string.
This function will work to generate a random string in PHP
Not the answer you’re looking for? Browse other questions tagged php random or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Long random string generator in PHP
Does anyone know how to generate a long (e.g. 280 characters) random string in PHP without having to use a for loop that will loop through characters 280 times? I need it in order to create a custom session ID.
The PHPSESSID is not secure enough in my opinion being too short and not too random. I know Facebook and Twitter, use long session IDs (150, 550 chars respectively).
4 Answers 4
If you’re asking a question like that, it probably means you don’t know anything about cryptography or security. Trying to generate a «long random string» because, as you say, «The PHPSESSID is not secure enough» will probably lead you to a custom and insecure implementation.
Generating a random string is IMPOSSIBLE, at least not with your current hardware: you may approximate a fair pseudorandom generator but that is only useful for educational purposes.
PHP’s Session ID generation algorithm is fairly efficient; if you think it is not secure enough, then you’ll likely waste time making it better. You may probably want to use a different authentication mechanism if you are looking at maximum security (using a client certificate for example).
If websites such as Twitter, Facebook, or another site with similar traffic use longer session IDs, it may be not because it is more secure (well in a way), but rather because it avoids conflicts.
Finally, if you want a longer session ID without trying to write your own algorithm, you should use the following PHP configuration directive:
session.hash_function which can take any hash algorithm known by PHP.
You may also increase the entropy by using a custom source (file) and setting the length of the seed:
Generate random string from 4 to 8 characters in PHP
I need to generate a string using PHP, it need to be unique and need to be from 4 to 8 characters (the value of a variable).
I thought I can use crc32 hash but I can’t decide how many characters, but sure it will be unique. In the other hand only create a «password generator» will generate duplicated string and checking the value in the table for each string will take a while.
Thanks!
Maybe I can use that :
Do you think I’ll get unique string each time for a goood while?
3 Answers 3
In short, I think you’ll get a pretty good random value. There’s always the chance of a collision but you’ve done everything you can to get a random value. uniqid() returns a random value based on the current time in microseconds. Specifying rand() (mt_rand() would be better) and the second argument as true to uniqid() should make the value even more unique. Hashing the value using md5() should also make it pretty unique as even a small difference in two random values generated should be magnified by the hashing function. idealmachine is correct in that a longer value is less likely to have a collision than a shorter one.
Your function could also be shorter since md5() will always return a 32 character long string. Try this:
The problem with randomness is that you can never be sure of anything. There is a small chance you could get one number this time and the same number the next. That said, you would want to make the string as long as possible to reduce that probability. As an example of how long such numbers can be, GUIDs (globally unique identifiers) are 16 bytes long.
In theory, four hex characters (16 bits) give only 16^4 = 65536 possibilities, while eight hex characters (32 bits) give 16^8 = 4294967296. You, however, need to consider how likely it is for any two hashes to collide (the «birthday problem»). Wikipedia has a good table on how likely such a collision is. In short, four hex characters are definitely not sufficient, and eight might not be.
You may want to consider using Base64 encoding rather than hex digits; that way, you can fit 48 bits in rather than just 32 bits.