Reputation: 31
I'm using Debian Bookworm and GMP library version 60201. I need to generate a random number with GMP library but I have 2 requirements, if possible, of course!
1 - Generate a number between 0 and a specific max value.
2 - Have some kind of entropy, preferrably from "/dev/urandom/" or anything better, but not too much complciated.
I have never worked with this library and I don't have any experience working with big numbers or cryptography, so, I've been trying to look at the docs, examples in the internet and even AI tools, but so far, I couldn't understand at least about the second point. I don't know if it is possible to use "/dev/urandom/" to get entropy or even if it is possible to add entropy using GMP library!
For the 1st point, I may have a solution, which is to generate random numbers while the generated number is not below the target max value. Not sure if this is the most efficient way, but seems to be a way!
Something like this:
do{
/*
code to generate a random number
*/
}while(randNumber > max_target_val);
For the second point, I see this in the docs: https://gmplib.org/manual/Random-State-Seeding
On some systems there’s a special device /dev/random which provides random data better suited for use as a seed.
But I can't find any suitable example on how to use "/dev/urandom/" with GMP library. Any help would be appreciated!
Upvotes: 1
Views: 160
Reputation: 9
If you need to generate numbers as seeds using /dev/urandom, the following code can assist you.
uint64_t random_num() {
FILE *fp = fopen("/dev/urandom", "rb");
uint64_t num = 0;
fread(&num, sizeof(uint64_t), 1, fp);
fclose(fp);
return num;
}
Upvotes: 0