Random number generator (RNG)

The qcrypto library API includes RNG functions.

See the library reference for detailed descriptions of the following functions:

RNG examples

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

#include <qcrypto/qcrypto.h>
#include <qcrypto/qcrypto_error.h>

#define RNG_BYTES			32

int main(void)
{
    int ret;
    qcrypto_ctx_t* qctx = NULL;
    const char* personal_str = "Hello World!";
    uint8_t result[RNG_BYTES];
    uint8_t seed = 200;

    /* Initialize the Qcrypto Library */
    ret = qcrypto_init(QCRYPTO_INIT_LAZY, NULL);
    if (ret != QCRYPTO_R_EOK) {
        fprintf(stderr, "qcryto_init() failed (%d:%s)\n", ret, qcrypto_strerror(ret));
        goto done;
    }

    /* Request drbg-ctr-128 */
    ret = qcrypto_rng_request("drbg-ctr-128", NULL, 0, &qctx);
    if (ret != QCRYPTO_R_EOK) {
        fprintf(stderr, "qcrypto_rng_request() failed (%d:%s)\n", ret, qcrypto_strerror(ret));
        goto done;
    }

    /* Initialize RNG arguments */
    qcrypto_rng_args_t rargs = {
        .drbg.pstr = (const uint8_t*)personal_str,
        .drbg.pstrsize = sizeof(personal_str),
    };

    /* Initialize an RNG */
    ret = qcrypto_rng_init(qctx, amp;rargs);
    if (ret != QCRYPTO_R_EOK) {
        fprintf(stderr, "qcrypto_rng_init() failed (%d:%s)\n", ret, qcrypto_strerror(ret));
        goto done;
    }

    /* Seed the RNG */
    ret = qcrypto_rng_seed(qctx, amp;seed, sizeof(seed));
    if (ret != QCRYPTO_R_EOK) {
        fprintf(stderr, "qcrypto_rng_seed() failed (%d:%s)\n", ret, qcrypto_strerror(ret));
        goto done;
    }

    /* Extracts a random value from the RNG */
    ret = qcrypto_rng_bytes(qctx, result, RNG_BYTES);
    if (ret != QCRYPTO_R_EOK) {
        fprintf(stderr, "qcrypto_rng_bytes() failed (%d:%s)\n", ret, qcrypto_strerror(ret));
        goto done;
    }

    /* Print the result */
    printf("The random value generated from PRNG is: ");
    for (int i=0; i<RNG_BYTES; i++) {
        printf("%02X", result[i]);
    }
    putchar('\n');
    goto done;

done:
    /* Release the RNG context handle */
    qcrypto_release_ctx(qctx);

    /* Uninitialize the Qcrypto Library */
    qcrypto_uninit();

    return ret;
}

#if defined(__QNXNTO__) && defined(__USESRCVERSION)
#include <sys/srcversion.h>
__SRCVERSION("$URL$ $Rev$")
#endif