-3

Runs before main:

 d -c 30 /dev/urandom > random.bytes   

Access the randomly generated numbers

int main() {
   FILE *fp;

   int fd = open("random.bytes",O_RDONLY);

    fp = fopen("file.txt" , "r");
   if (fd < 0) {
        fprintf(stderr, "%s\n", strerror(errno));

    }

    char buffer[8];
    //int error =  read(fd,buffer,sizeof(buffer) );

    if( fgets (buffer,sizeof(buffer), fp)!=NULL ) {
          /* writing content to stdout */
          puts(buffer);
             }
   fclose(fp);


    if ( error < 0) {
              fprintf(stderr, "%s\n", strerror(errno));

                }
    uint8_t tid = atoi(buffer);
    printf("%d\n",tid); 

    return 0;
}

Output is always 0?

closed as off-topic by forest, Tom K., Tobi Nary, schroeder Apr 23 '18 at 10:26

  • This question does not appear to be about Information security within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

  • This appears to be a programming question rather than a security question. Perhaps it's because your read call is commented out? – AndrolGenhald Apr 20 '18 at 21:22
  • Nope read wasn't working so I switched to fgets – jamarcus_13 Apr 20 '18 at 22:45
  • You're calling fgets on fp which is a handle to file.txt, not random.bytes – AndrolGenhald Apr 20 '18 at 22:51
1

Instead of reading from a random dump, you should read from urandom directly:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(){
        int i;
        unsigned char buffer[8];
        int fd = open("/dev/urandom", O_RDONLY);
        read(fd, buffer, 8);
        //buffer now contains the random data
        close(fd);
        for(i = 0; i < 8; ++i)
                printf("%02X", buffer[i]);
        printf("\n");
        return 0;
}
  • good answer, any idea as to why my previous code wasn't working? – jamarcus_13 Apr 20 '18 at 22:43
  • Why O_RDWR instead of O_RDONLY? – forest Apr 21 '18 at 13:41
  • @forest Supposedly writing to urandom won't cause any negative effects, so I figured it might as well open as read write in case the user wants to write to it. If it's early in the boot phase and the system doesn't have writable disks for storing entropy from the previous run then it might be worthwhile to read data from an external server to write it to urandom. – user Apr 23 '18 at 12:00
  • @user That's true, but it's usually a good idea to only open a file with the mode you need. And as for writing to the entropy pool early at boot, I think it's not immediately useful due to the way the kernel collects entropy. – forest Apr 23 '18 at 13:26
  • @forest I agree that in this case it doesn't make sense to open it as read/write. – user May 24 at 18:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.