1

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.

  • 2
    [This is probably what you're looking for](https://stackoverflow.com/questions/822323/how-to-generate-a-random-int-in-c/39475626#39475626) – Adalcar Feb 11 '21 at 14:56
  • Re “I use GMP's Linear congruential Algorithm to generate random number in C”: Are you saying you want to use a high-quality truly random source for the seed and then you will use a simple linear congruential algorithm to generate numbers from it? That is not a good idea. – Eric Postpischil Feb 11 '21 at 15:12
  • @EricPostpischil Thanks for comment. what's your suggestion for a high-quality random number? which algorithm should I use? –  Feb 11 '21 at 16:26
  • Is there a reason you're not using a crypto library for this? It should use the best available source of randomness to generate its keys. – Barmar Feb 11 '21 at 16:34
  • @Barmar Thanks for comment. which library you suggest? the only good library i know is openssl. –  Feb 11 '21 at 16:44
  • I've never written any crypto code, so I can't recommend anything specific. – Barmar Feb 11 '21 at 16:54
  • You could use for example [HMAC-DRBG](https://botan.randombit.net/handbook/api_ref/rng.html#hmac-drbg). For seeding, you would use either `/dev/random` / `/dev/urandom` as suggested in the answer or a hardware-based RNG source (depending on what you have available, e.g. from a TPM, a PKCS#11 smartcard or a processor-specific provider). – f9c69e9781fa194211448473495534 Feb 11 '21 at 20:33
  • Have you read the [gmp docs](https://gmplib.org/gmp-man-6.0.0a.pdf)? Check section 9.2. Does this help? – Joseph Wood Feb 11 '21 at 23:37

1 Answers1

0

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.

lfalkau
  • 896
  • 7
  • 21