Search code examples
clibsodium

Pseudo Random number generation in C using libsodium


I am trying to create a sequence of integers which is the same everytime as the generator is seeded however I am struggling to get it working. Right now the sequence is never the same.

#include "sodium.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

main()
{
    if (sodium_init() == -1)
    {
        return 1;
    }

    unsigned int myInts[128];
    char seed[randombytes_SEEDBYTES] = "a seeeeeed";
    printf("%s", seed);

    randombytes_buf_deterministic(myInts, 128, seed);

    for (int i = 0; i < 128; i++)
    {
        printf("\n(%u)", myInts[i]);
    }
}

Solution

  • The problem is, that here

    randombytes_buf_deterministic(myInts, 128, seed);
    

    you generate 128 bytes of pseudorandom-data, but your buffer

    unsigned int myInts[128];
    

    is sizeof(int)*128 bytes big. So you have to generate enough data with

    randombytes_buf_deterministic(myInts, sizeof(myInts), seed);
    

    to fill the whole buffer with deterministic values. Then it should give the output you expect.