364,036 Members | 5273 Browsing Online
Community for Developers & IT Professionals
Bytes IT Community

Random number generation

puneetsardana88
P: 57
Hi

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

Expand|Select|Wrap|Line Numbers
  1. void fill_random_key(char *key)
  2. {
  3.     /* Length of the key */
  4.     unsigned short int length = KEYLENGTH;
  5.  
  6.     /* Seed number for rand() */
  7.     srand((unsigned int) time(0) + getpid());
  8.     int i=0;
  9.  
  10.     while(length--) {
  11.         key[i]=rand() % 127;
  12.         srand(rand());
  13.  
  14.         i++;
  15.  
  16.     }
  17. }
  18.  
  19. void get_keys_for_files(char **files)
  20.  {
  21.     extern int num_of_files;
  22.     char (*curr_file)[20]=files;
  23.  
  24.     char key[32];
  25.     int i=0;
  26.     FILE *fp;
  27.     char key_file[1024];
  28.     for(i=0;i<num_of_files;i++)
  29.      {
  30.  
  31.         strcpy(key_file,cwd);
  32.         strcat(key_file,"\\keys\\");
  33.         strcat(key_file,curr_file);
  34.         fill_random_key(key);
  35.         fp=fopen(key_file,"w");
  36.         fputs(key,fp);
  37.         curr_file++;
  38.         fclose(fp);
  39.         sleep(1000);
  40.      }
  41.  }
  42.  
  43.  
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
Jan 29 '12 #1

✓ answered by Rabbit

That's because you're seeding with the same number otherwise. You need to move on to the next number in the sequence.
Share this Question
Share on Google+
4 Replies


Rabbit
Expert Mod 5K+
P: 6,652
That's because you're seeding with the same number otherwise. You need to move on to the next number in the sequence.
Jan 29 '12 #2

puneetsardana88
P: 57
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
Jan 30 '12 #3

Rabbit
Expert Mod 5K+
P: 6,652
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.
Jan 30 '12 #4

3108balu
P: 1
import java.util.Random;


public class RandomGen {

public static void main(String[] args) {

Random r=new Random();
System.out.println(r.nextInt(1001) + r.nextInt(9000));
}
}
Jan 31 '12 #5

Post your reply

Help answer this question



Didn't find the answer to your C / C++ question?

You can also browse similar questions: C / C++