Advertisement
deisner

rand_ioctl.c

Feb 16th, 2012
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.29 KB | None | 0 0
  1. #include <fcntl.h>
  2. #include <linux/types.h>
  3. #include <linux/random.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <sys/ioctl.h>
  7. #include <sys/stat.h>
  8. #include <sys/types.h>
  9.  
  10. #define MAX_BYTES   512
  11. #define MAX_BITS    (8 * MAX_BYTES)
  12.  
  13. struct my_rand_pool_info {
  14.     int entropy_count;
  15.     int buf_size;
  16.     unsigned char buf[MAX_BYTES];
  17. } rpi;
  18.  
  19.  
  20. static ssize_t
  21. add_entropy(size_t nbits)
  22. {
  23.     int fd = open( "/dev/random", O_RDWR);
  24.     if (fd < 0) {
  25.         perror( "Cannot open /dev/random");
  26.         return -1;
  27.     }
  28.  
  29.     rpi.entropy_count = nbits;
  30.     rpi.buf_size = 1;
  31.     rpi.buf[0] = 0;
  32.  
  33.     if (ioctl(fd, RNDADDENTROPY, &rpi) == -1) {
  34.         perror("ioctl");
  35.         return -1;
  36.     }
  37.     return rpi.entropy_count;
  38. }
  39.  
  40.  
  41. int main( int argc, char *argv[]) {
  42.  
  43.     int nbits = 0;
  44.  
  45.     if (argc < 2) {
  46.         fprintf( stderr, "Usage: rand_ioctl <num bits>\n");
  47.         exit(1);
  48.     }
  49.  
  50.     nbits = atoi( argv[1]);
  51.     if (nbits <= 0)
  52.         exit(0);
  53.     else if (nbits > MAX_BITS)
  54.         nbits = MAX_BITS;
  55.  
  56.     printf( "Adding %d bits of fake entropy to the pool.\n", nbits);
  57.  
  58.     ssize_t nbits_added = add_entropy( nbits);
  59.  
  60.     if (nbits_added >= 0) {
  61.         printf( "%d bits added.\n", nbits_added);
  62.         exit(0);
  63.     }
  64.     else
  65.         exit(1);
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement