英文:
What techniques can I use to determine the number generated by srand() in C?
问题
如何从 srand((uint32_t)timer)
中知道秘密数字,其中 time_t timer = time(NULL)
。
我无法察觉到 rand()
中的任何模式。我如何利用一种方法使 input == rand()
?
英文:
How to know the secret number from srand((uint32_t)timer) where time_t timer = time(NULL)
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printTerminalTime(time_t t) {
char buffer[32];
struct tm* tm_info = localtime(&t);
strftime(buffer, 32, "%H:%M:%S > ", tm_info);
printf("%s", buffer);
}
int main() {
setbuf(stdout, NULL);
time_t timer = time(NULL);
srand((uint32_t)timer);
printTerminalTime(timer);
printf("%s", "Please enter your password: ");
uint32_t input = 0;
scanf("%u", &input);
if (input == rand()) {
puts(getenv("FLAG"));
} else {
printTerminalTime(time(NULL));
puts("Access denied!");
}
return 0;
}
I can't perceive any pattern in rand(). How can I utilize a method to make input == rand()?
答案1
得分: 3
使用srand()
提供的特定种子,在后续调用rand()
时生成的伪随机数序列在给定环境(系统+编译器)中是固定的。
因此,知道种子就可以预测rand()
的结果。不知道种子则非常困难。
我不太确定您的目标是什么,但打印/存储种子的值将提供必要的信息:
...
#include <inttypes.h>
...
uint32_t seed = (uint32_t)timer;
srand(seed);
printf("seed=%" PRIu32 "\n", seed);
...
然后,拥有第二个程序将允许您计算相应的rand()
结果:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
int main() {
uint32_t input = 0;
printf("Enter seed: ");
scanf("%" SCNu32, &input);
srand(input);
printf("Password: %" PRIu32 "\n", (uint32_t)rand());
return 0;
}
如果您选择使用固定的种子,而不是基于time(NULL)
的种子,那么可以将该种子输入到第二个程序中以获取相应的"密码"。
英文:
Providing a given seed with srand()
, the sequence of pseudo-random numbers generated by subsequent calls to rand()
is fixed in a given environment (system+compiler).
Thus, knowing the seed makes it possible to predict the result of rand()
. Not knowing the seed makes it very hard.
I am not quite sure what your goal is, put printing/storing the value of the seed will provide the necessary information:
...
#include <inttypes.h>
...
uint32_t seed = (uint32_t)timer;
srand(seed);
printf("seed=%" PRIu32 "\n", seed);
...
Having a second program will then allow you to calculate the corresponding rand()
result:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
int main() {
uint32_t input = 0;
printf("Enter seed: ");
scanf("%" SCNu32, &input);
srand(input);
printf("Password: %" PRIu32 "\n", (uint32_t)rand());
return 0;
}
If you choose to use a fixed seed, instead of one based on time(NULL)
, then that seed can be entered into the second program to get the corresponding "password".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论