I'm trying to fill an array, where each entry is four bytes, with "gcry_randomize".
I thought because a long is represented by 4 byte and I only need positive numbers, I use a unsigned long pointer array with 64 entries. Then I used the gcry_randomize function to fill each entry with four bytes and tried to print it out. There is an compiler error about printf-function but it is working.
unsigned long int* random_numbers[64];
for(index = 0; index < 64; index++){
gcry_randomize( random_numbers[index], 4, GCRY_STRONG_RANDOM);
printf("Random number: %lu \n", random_numbers[index]);
}
However, the result is not really random and not in the size I expected (4 bytes instead of just 1 byte):
Random Number 0: 32535136
Random Number 1: 32535168
Random Number 2: 32535200
Random Number 3: 32535232
Random Number 4: 32535264
Should I change the pointer to unsigned char pointer and then cast it to a long integer? The next step of my code will be calculating that number in modulus so it's necessary to have a long integer. Another option would be creating a random char string of 256 bytes and then split the string into 4 byte parts, casting it to a long and save it. The problem I had with that approach is that I don't know how to read a specific part of a char string.
gcry_randomize
fills a buffer with random bytes. So, what you might get is 4 or 8 random bytes, depending on your architecture.
You can do this when you do
unsigned long int random_numbers[64];
for(index = 0; index < 64; index++) {
gcry_randomize(&random_numbers[index], sizeof(random_numbers[index]), GCRY_STRONG_RANDOM);
printf("Random number: %lu \n", random_numbers[index]);
}
What you have done before is passing an uninitialized pointer to gcry_randomize, which results in undefined behaviour.
Update:
There is no need to dynamically allocate memory. If you want to put the random bytes in a separate array first, you can just use a byte array on the stack
unsigned char buf[4];
gcry_randomize(buf, sizeof(buf), GCRY_STRONG_RANDOM);