- Генерация паролей в PHP
- Функции генерации паролей
- Генерация пароля на основе массива символов:
- На основе строки:
- На основе функции str_shuffle():
- Хранение в базе данных
- Хеширование пароля:
- Проверка:
- Generating Random MD5 Hash Using PHP and JavaScript
- MD5 random generate code duplicate
- How can I limit the md5() function PHP to generate 8 random caharacters and numbers?
- Generate rand hash by md5 and sha1
- Adding an MD5 Hash to my password Generator
- PHP Program to generate a hash code from random value
- How to generate hash code using PHP?
- ALGORITHM
- How to Generate a Random String with PHP
- Using the Brute Force
- Applying Hashing Functions
- Applying the Uniqid() Function
- Using Random_bytes() Function ( The Most Secured)
Генерация паролей в PHP
В PHP есть несколько функций для генерации случайного числа, это:
- rand($min, $max) – на платформах Windows $max может быть не больше 32767. С версии PHP 7.1 стала синонимом функции mt_rand() .
- mt_rand($min, $max) – генерирует случайное значение на базе Вихря Мерсенна (не генерирует криптографически безопасные значения).
- random_int($min, $max) – генерирует случайные целые числа, пригодные для использования в криптографических целях (появилась в PHP 7.0).
На их основе можно сформировать пароли высокой сложности:
Функции генерации паролей
Генерация пароля на основе массива символов:
function gen_password($length = 6) < $password = ''; $arr = array( 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' ); for ($i = 0; $i < $length; $i++) < $password .= $arr[random_int(0, count($arr) - 1)]; >return $password; > echo gen_password(8);
На основе строки:
function gen_password($length = 6) < $chars = 'qazxswedcvfrtgbnhyujmkiolp1234567890QAZXSWEDCVFRTGBNHYUJMKIOLP'; $size = strlen($chars) - 1; $password = ''; while($length--) < $password .= $chars[random_int(0, $size)]; >return $password; > echo gen_password(8);
Для более старых версий PHP, необходимо прописать функцию random_int() :
if (!function_exists('random_int')) < function random_int($min, $max) < if (!function_exists('mcrypt_create_iv')) < trigger_error('mcrypt must be loaded for random_int to work', E_USER_WARNING); return null; >if (!is_int($min) || !is_int($max)) < trigger_error('$min and $max must be integer values', E_USER_NOTICE); $min = (int)$min; $max = (int)$max; >if ($min > $max) < trigger_error('$max can\'t be lesser than $min', E_USER_WARNING); return null; >$range = $counter = $max - $min; $bits = 1; while ($counter >>= 1) < ++$bits; >$bytes = (int)max(ceil($bits/8), 1); $bitmask = pow(2, $bits) - 1; if ($bitmask >= PHP_INT_MAX) < $bitmask = PHP_INT_MAX; >do < $result = hexdec(bin2hex(mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM))) & $bitmask; >while ($result > $range); return $result + $min; > >
На основе функции str_shuffle():
str_shuffle() – переставляет символы в строке случайным образом, но не рекомендуется использование в криптографических целях.
function gen_password($length = 6) < $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return substr(str_shuffle($chars), 0, $length); >echo gen_password(8);
Хранение в базе данных
Пароли в БД не должны хранится в открытом виде, для создания хешей и их проверки есть функции на основе автоматической соли.
Хеширование пароля:
$hash = password_hash('123456', PASSWORD_DEFAULT); echo $hash; // $2y$10$hqpo2yrbT.82aQkqFiRkie1Y09lhkijK5DtnoBQHDxEBWo/junDR6
Проверка:
$hash = '$2y$10$hqpo2yrbT.82aQkqFiRkie1Y09lhkijK5DtnoBQHDxEBWo/junDR6'; if (password_verify('123456', $hash)) < echo 'Пароль правильный!'; >else
Generating Random MD5 Hash Using PHP and JavaScript
Utilizing the md5 algorithm in conjunction with a randomized code, the customer_id, and the present date and time, I’ve generated a hash code. After processing 200,000 records, I’ve encountered numerous duplicates. To decrease the likelihood of collisions, it would be more prudent to use a hashing algorithm with a greater number of bits.
MD5 random generate code duplicate
To generate a unique hash code, I utilize md5 encryption along with random code , current datetime, and customer_id. However, after processing 200,000 records, I discovered numerous duplicates. Is there a way to prevent this from happening?
while ($row = mysql_fetch_array($result, MYSQL_NUM))
Utilize current time stamp (i.e. time()) in place of the present date.
The value of $hash is generated by applying the md5 function to a combination of a random number between 0 and 100,000, the current time in seconds since Unix Epoch, and the first element of a given row.
The issue lies in the fact that multiple entries could have the same time, as you are only measuring up to seconds. To address this, consider measuring milliseconds and nanoseconds or taking breaks between generations.
It is advisable to opt for a hashing algorithm that expends more bits for hashing to minimize the likelihood of collisions.
add the timestamp to your md5
$hash = md5(rand(0,100000)+strtotime(date('curr_date'))+$row[0])."_".time();
rand(0,100000) . strtotime(date('c')) . $row[0]
By increasing the number of possible plaintexts for the hash, you can significantly decrease the number of collisions.
How to generate a random, unique, alphanumeric string, There are many ways to generate a random, unique, alphanumeric string in PHP which are given below: Using str_shuffle () Function: The str_shuffle () function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter. When a number is …
How can I limit the md5() function PHP to generate 8 random caharacters and numbers?
What steps should I take to ensure that only 8 instances of mixed characters are produced by the given code, along with any other numbers present?
An md5 is essentially a 32-character long hash.
You have the option to utilize just a portion of the string produced by the md5() function, specifically eight characters, when using the substr function.
An illustration of keeping the initial eight characters could be achieved by implementing a code similar to this:
echo substr(md5(uniqid(rand(1,6))), 0, 8);
And this would yield a result similar to this:
Php — JavaScript File Hash Value Generate with Part of, Yes, you can do that and it is called Progressive Hashing. var md5 = CryptoJS.algo.MD5.create (); md5.update («file part 1»); md5.update («file part 2»); md5.update («file part 3»); var hash = md5.finalize (); Can I specify any amount of Byte such as 2000 Character of a file to generate HASH Value then generating …
Generate rand hash by md5 and sha1
By utilizing this method, I can achieve a dual-layered encryption system that will ultimately produce a 32-length output hash.
How can I make the hash a length of 255 (for instance)?
Cease your current activity immediately.
Using identical or distinct cryptographic functions repeatedly does not provide multiple layers of encryption. In fact, it can compromise the strength of the encryption by simplifying the discovery of a hash collision.
Additionally, both md5 and sha-1 lack cryptographic security.
When creating passwords, it is recommended to utilize bcrypt or PBKDF2 only one time. Additionally, ensure a unique salt and high iteration count are employed.
To generate more bytes, you can utilize a KBKDF function like the ones mentioned in nist sp 800-108 or HKDF. It’s important to note that doing so won’t enhance the security level to match the number of bytes in the output.
Generating secure random numbers requires methods other than rand() . No hash or KDF can be relied upon for this purpose.
Opt for mcrypt_create_iv ($size, MCRYPT_DEV_URANDOM) that comes with a convenient $size parameter, which will address your length issue simultaneously.
PHP md5() Function, The md5 () function calculates the MD5 hash of a string. The md5 () function uses the RSA Data Security, Inc. MD5 Message-Digest Algorithm. From RFC 1321 — The MD5 Message-Digest Algorithm: «The MD5 message-digest algorithm takes as input a message of arbitrary length and produces as output a 128-bit «fingerprint» …
Adding an MD5 Hash to my password Generator
Attempting to include an MD5 hash in the password generator used in my registration code for the custom moodle platform.
"; echo "Last name:" . $_POST['lastname'] . "
"; echo "Email:" . $_POST['email'] . "
"; echo "Password:" . $PASSWORD; ?>
I have attempted to hash it multiple times, however, it does not appear to be getting hashed. I am uncertain about how to verify it, but it seems to be not hashing.
I would be grateful for any guidance on how to conduct a test for this.
To obtain an 8-character random password, simply eliminate the following line: $n = Md5(rand(0, $alphaLength)); and replace it with $pass[] = $alphabet[rand(0, $alphaLength)]; . This approach works well.
Hash — is there any method in javascript to genetare, The first parameter is the message to be converted to a Hash, from your example it the imploded string of a empty array, so basically a empty string, i don’t know why you wish to hash a empty string, but equivalent code will be var hash = CryptoJS.HmacMD5(«»,»hshalslkaslfhalkfhalsksaas»); –
PHP Program to generate a hash code from random value
The PHP language comes with several functions to hash a string based on different algorithms like «sha1», «sha256», «md5» etc. These functions all take a string as an argument and output an Alpha-Numeric hashed string.
string hash($algo, $string, $getRawOutput)
How to generate hash code using PHP?
In this program, we are generating the hash code from a random value. For that first, we have to assign the random value to the variable str the random value is generated using the built-in function rand(). The to generate the hashing code by using the built-in function hash() with ‘sha256′(string-based algorithm for generating the hash code) and value of the variable str as the arguments of the function and assign the value into the variable hashedCode and after that, we can print the value of the variable hashedCode as the generated hash code.
ALGORITHM
Step 1: Assign a random value using the built-in function rand() to the variable str
Step 2: Generate the hashing code by using the built-in function hash() with ‘sha256′(string-based algorithm for generating the hash code) and value of the variable str as the arguments of the function and assign the value into the variable hashedCode
Step 3: Print the value of the variable hashedCode as the generated hash code
How to Generate a Random String with PHP
In the framework of this snippet, we will explain several ways of generating a unique, random string with the help of PHP arsenal.
Using the Brute Force
The first way is using the brute force. It is the simplest method that can be achieved by following the steps below:
- Storing all the possible letters into strings.
- Generating a random index from 0 to the length of the string -1 .
- Printing the letter on the given index.
- Implementing the steps n times ( n is considered the length of the required string).
$n = 10; function getRandomString($n) < $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randomString = ''; for ($i = 0; $i < $n; $i++) < $index = rand(0, strlen($characters) - 1); $randomString .= $characters[$index]; > return $randomString; > echo getRandomString($n);
Applying Hashing Functions
In PHP, there are several functions such as md5() , sha1() , and hash() that might be applied for hashing a string based on exact algorithms such as “sha1”, “sha256”, “md5”, and so on.
All of these functions are capable of taking a string as an argument and output an Alpha-Numeric hashed string.
After understanding how to utilize the functions, the next steps become simpler:
- Generating a random number with the rand() function.
- Hashing it with one of the functions above.
$str = rand(); $result = md5($str); echo $result; ?>
The output will look like this:
2e437510c181dd2ae100fc1661a445d4
Applying the Uniqid() Function
This is an inbuilt function that is applied for generating a unique ID built on the current time in microseconds. It returns a 13-character long unique string, by default.
The example is demonstrated below:
$result = uniqid(); echo $result; ?>
The first output is the following:
Please, take into consideration that all the methods above are based on rand() and uniqid() functions. However, they are not considered cryptographically secure random generators.
Using Random_bytes() Function ( The Most Secured)
If you want to generate cryptographically secure pseudo random bytes that can be converted into a hexadecimal format with the bin2hex() function, then you should use the random_bytes function.
$n = 20; $result = bin2hex(random_bytes($n)); echo $result; ?>
235aed08a01468f90fa726bd56319fb893967da8
508b84494cdf31bec01566d12a924c75d4baed39
So, in this snippet, we represented several ways to generate a random string with PHP. Learning them will make your work easier and more productive.