-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?

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

1 Answer 1

2

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;
}
5
  • good answer, any idea as to why my previous code wasn't working? Commented Apr 20, 2018 at 22:43
  • Why O_RDWR instead of O_RDONLY?
    – forest
    Commented Apr 21, 2018 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
    Commented Apr 23, 2018 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
    Commented Apr 23, 2018 at 13:26
  • @forest I agree that in this case it doesn't make sense to open it as read/write.
    – user
    Commented May 24, 2019 at 18:22

Not the answer you're looking for? Browse other questions tagged .