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

jamarcus_13
  • 1
  • 1
  • 1
  • 3

1 Answers1

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;
}
user
  • 616
  • 7
  • 11
  • 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](https://security.stackexchange.com/q/183506/165253) 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 '19 at 18:22