Random number generation

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • puneetsardana88
    New Member
    • Aug 2009
    • 57

    Random number generation

    Hi

    I am generating 256 bit key for AES. I am using the following implementation

    Code:
    void fill_random_key(char *key)
    {
        /* Length of the key */
        unsigned short int length = KEYLENGTH;
    
        /* Seed number for rand() */
        srand((unsigned int) time(0) + getpid());
        int i=0;
    
        while(length--) {
            key[i]=rand() % 127;
            srand(rand());
    
            i++;
    
        }
    }
    
    void get_keys_for_files(char **files)
     {
        extern int num_of_files;
        char (*curr_file)[20]=files;
    
        char key[32];
        int i=0;
        FILE *fp;
        char key_file[1024];
        for(i=0;i<num_of_files;i++)
         {
    
            strcpy(key_file,cwd);
            strcat(key_file,"\\keys\\");
            strcat(key_file,curr_file);
            fill_random_key(key);
            fp=fopen(key_file,"w");
            fputs(key,fp);
            curr_file++;
            fclose(fp);
            sleep(1000);
         }
     }
    The problem with this code is that if I remove sleep it will give same keys for almost all files. But I do not want to deter performance of my module due to this. Can somebody let me know better implementation? rand_s() is not available. I am working on code blocks : mingw.


    Thanks for your help
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    That's because you're seeding with the same number otherwise. You need to move on to the next number in the sequence.

    Comment

    • puneetsardana88
      New Member
      • Aug 2009
      • 57

      #3
      Yes I am looking for a method in which I can generate randon numbers without using sleep. (with sleep i can pass different seed) but i am looking for an alternative to sleep so that performance do not deter

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        I'm saying that you're seeding with the same number each time it's called. That's why you're getting the same key. The solution is simple, just seed once, or include your loop value in the seed. You don't need sleep and you don't need an alternative to sleep. Also, you don't need to reseed everytime to get the next character.

        Comment

        • 3108balu
          New Member
          • Jan 2012
          • 1

          #5
          import java.util.Rando m;


          public class RandomGen {

          public static void main(String[] args) {

          Random r=new Random();
          System.out.prin tln(r.nextInt(1 001) + r.nextInt(9000) );
          }
          }

          Comment

          Working...