Search code examples
cpublic-key-encryptionprivate-keygmpdiffie-hellman

How to generate random seed for random numbers


I'm trying to generate big random numbers for the public key and private key. I have problem with the initial seed to generate a random 256-bit private key on client-side. as you may know, we shouldn't use rand or srand function in C because it's easy to break.
how can I generate a random seed to generate a random 256-bit private key?
I use GMP's Linear congruential Algorithm to generate random number in C.


Solution

  • On unix systems, you can read from /dev/random and /dev/urandom files to get some "randomness" byte sequences. Those sequences are based on your system entropy. See this post for more details about their differences.

    #include <unistd.h> // read
    #include <fcntl.h>  // open
    #include <stdio.h>  // printf
    
    int main(void)
    {
        int             fd;
        unsigned int    seed;
    
        fd = open("/dev/urandom", O_RDONLY);
    
        read(fd, &seed, sizeof seed);
    
        printf("%u\n", seed);
    
        //  Then you can use srand with your new random seed
    
        return (0);
    }
    

    Note: Don't forget to check for errors after open and read, and to close fd after use.