The post has been translated automatically. Original language: Russian
Imagine that in the game you open three chests. The first one drops a sword, the second one drops a potion, and the third one drops coins. You restart the game, open the chests again and receive the same rewards in the same order. This is possible if the random number generator was started both times with the same initial value.
Why "random" numbers can be repeated
Many programs use a pseudorandom number generator. With each call, it calculates the next number and updates its internal state. The initial value from which this process begins is called the seed, or seed of the generator. If you use the same algorithm, the same seed, and the same sequence of calls, the result will repeat.
This is convenient for the developer. Let's say the game accidentally created a level where the character is stuck between the walls. By saving the seed, you can get the same level again and check if the fix helped.
When numbers should be unpredictable
The password reset link has a different task. It contains a secret token that should be almost impossible for an outsider to guess. A cryptographically strong generator is used for this purpose. It also works according to an algorithm, and its internal state is formed using data from entropy sources. In this context, entropy shows how much unpredictability is contained in the source data.
In Python, the random module is suitable for games, simulations, and reproducible tests. For secret tokens, there are secrets, which uses the operating system's source of randomness.
What does lava lamps have to do with it?
A wall of lava lamps was installed in the Cloudflare office in San Francisco and a camera was pointed at it. The wax in the lamps heats up, rises, cools and falls. Its droplets are constantly changing shape and position, so the frames provide data that is difficult to predict in advance.
Cloudflare named this system LavaRand. It processes the image from the camera and uses the received data as an additional source of entropy for its servers. The lamps provide unpredictable inputs, and the algorithm generates a stream of numbers based on them. Therefore, the server does not have to wait for the next drop of wax to rise in the lamp.
Представьте, что в игре вы открываете три сундука. Из первого выпадает меч, из второго — зелье, из третьего — монеты. Вы перезапускаете игру, открываете сундуки снова и получаете те же награды в том же порядке. Такое возможно, если генератор случайных чисел оба раза запустился с одним и тем же начальным значением.
Почему «случайные» числа можно повторить
Во многих программах работает генератор псевдослучайных чисел. При каждом вызове он вычисляет очередное число и обновляет своё внутреннее состояние. Начальное значение, с которого начинается этот процесс, называют seed, или зерном генератора. Если использовать тот же алгоритм, тот же seed и ту же последовательность вызовов, результат повторится.
Для разработчика это удобно. Допустим, игра случайно создала уровень, на котором персонаж застрял между стенами. Сохранив seed, можно заново получить тот же уровень и проверить, помогло ли исправление.
Когда числа должны быть непредсказуемыми
У ссылки для сброса пароля другая задача. Она содержит секретный токен, который постороннему должно быть практически невозможно угадать. Для этого используют криптографически стойкий генератор. Он тоже работает по алгоритму, а его внутреннее состояние формируется с помощью данных из источников энтропии. В этом контексте энтропия показывает, сколько непредсказуемости содержится в исходных данных.
В Python для игр, симуляций и воспроизводимых тестов подходит модуль random. Для секретных токенов есть secrets, который использует источник случайности операционной системы.
При чём тут лавовые лампы?
В офисе Cloudflare в Сан-Франциско установили стену из лавовых ламп и направили на неё камеру. Воск в лампах нагревается, поднимается, остывает и опускается. Его капли постоянно меняют форму и положение, поэтому кадры дают данные, которые трудно предсказать заранее.
Cloudflare назвала эту систему LavaRand. Она обрабатывает изображение с камеры и использует полученные данные как дополнительный источник энтропии для своих серверов. Лампы дают непредсказуемые исходные данные, а алгоритм на их основе генерирует поток чисел. Поэтому серверу не приходится ждать, пока в лампе поднимется очередная капля воска.
Comments 3
Newest Popular