1

I am working on a project and I'm noticing a peculiar behavior that I was hoping someone could tell me if it is correct or not.

I have a program that is trying to generate some random numbers using BN_rand(). Snippet of code follows:

BIGNUM *test = NULL;
unsigned char buffer[2048];
int fd = open("/dev/urandom", O_RDWR);
read(fd, buffer, 2048);
close(fd);

test = BN_new();
if (RAND_status() != 1)
    goto error3;

RAND_seed(buffer, 2048);

if (!BN_rand(test,2048,0,1))
    goto error3;

do_bn_print_name(stdout, "test", test);

Every time I run this program though, it gives me the same random number. I was expecting the number to be changing after every run. Am I doing this right or is this expected behavior?

Thanks for any assistance!

Toby
  • 21
  • 4
  • You can seed directly from a file using int rc = RAND_load_file("/dev/urandom", 32); if(rc != 32) { /* RAND_load_file failed */ } – MCCCS Jul 26 '18 at 17:04
  • Thanks! That didn't fix my issue but it did answer my question! It also led me to my bigger issue which is way out of scope of my original question. – Toby Jul 26 '18 at 19:03
  • Sorry, I had to do some reading and it seems the RAND_load_file is not available to me in FIPS mode according to the OpenSSL FIPS user guide. Sorry I should have mentioned this in the OP. I switched to using RAND_byte() instead of BN_rand but I am still producing the same random numbers every time I execute. – Toby Jul 27 '18 at 04:34

1 Answers1

1

I couldn't reproduce the issue since you used some custom functions, but this works for me:

#include <openssl/bn.h>
#include <openssl/rand.h>
#include <stdio.h>

int main(void) {
    BIGNUM *test = NULL;
    unsigned char buffer[2048];
    FILE* fd = fopen("/dev/urandom", "r");
    fread(buffer, 1, 2048, fd);
    fclose(fd);

    test = BN_new();
    if (RAND_status() != 1)
        printf("Not enough entropy\n");

    RAND_seed(buffer, 2048);

    if (!BN_rand(test,2048,0,1))
        printf("Not enough entropy\n");

    printf("%s", BN_bn2dec(test));
    return 0;
}
MCCCS
  • 731
  • 1
  • 7
  • 15
  • Thanks! I stopped working on the original program and started from scratch and everything is working good now. Thanks again for the help! – Toby Jul 27 '18 at 12:41