Sujal Sheth
Sujal Sheth

Reputation: 392

How to generate Random number of 12 bytes?

I'm working on project on linux in C and in which i need to generate random number of 12 bytes. I have searched over internet but i couldn't find any other than srand or random function. But these functions can only generate random number of 32-bit(4 byte).

I'm looking for generating random number of 12 byte.

Does anybody know anything library on linux which provide this functionality ?

Upvotes: 0

Views: 6446

Answers (2)

You did not tell what 12 random bytes mean to you, and why you need them.

You should read random(4) then perhaps code

unsigned char myrandbytes[12];
FILE* fr = fopen("/dev/urandom", "r");
if (!fr) perror("urandom"), exit(EXIT_FAILURE);
fread(myrandbytes, sizeof(char), 12, fr);
fclose(fr), fr = NULL;

But very often, using rand(3) as suggested in that answer should be enough. You could also use random(3) or lrand48(3). I am usually happy enough with random(3) which I usually seed -e.g. with srandom or initstate by reading /dev/urandom at start time.

Since you did not tell us why you need random numbers, we cannot help more.

If the quality of the random number is very important (e.g. for strong cryptographic purposes), it might be much more hard than you think, and it is system and hardware dependent (read again the random(4) page).

Upvotes: 3

user529758
user529758

Reputation:

OK so finally a solution:

unsigned char buf[12];
int i;
srand(time(NULL));
for (i = 0; i < sizeof(buf); i++) {
    buf[i] = rand() % 256;
}

(Yes, I'm using modulo - if you care about uniform distribution, don't use it.)

Upvotes: 6

Related Questions