Random Numbers and Hashing

Introduction

The C-Craft library contains basic random number generators and hashing.

Random Number Generators

Random numbers may be generated like so.

#include <c-craft/rng.h>

MEM_SCOPE mem = sm_create(0);
RNG rng = rng_xor_create(mem)

unsigned long x = rng_next(rng);

This library provides two random number generators. They both follow the same function pattern and are interchangeable. Which one you choose depends on your needs.

Basic Standard

The basic UNIX C rand() function. This generates integers in the range 0 to INT_MAX. IE 31 bits on most modern computers.

#include <c-craft/rng.h>

MEM_SCOPE mem = sm_create(0);
RNG rng = rng_std_create(mem)

unsigned long x = rng_next(rng);

XOR

This is a simple but fast bit crunching algorithm based on a bitwise shift and XOR operation and generates numbers in the range 0 to ULONG_MAX. IE 64 bits on most modern computers.

#include <c-craft/rng.h>

MEM_SCOPE mem = sm_create(0);
RNG rng = rng_xor_create(mem)

unsigned long x = rng_next(rng);

Random Numbers

Once you have a generator you can generate different types of numbers with a RANDOM.

#include <c-craft/rand.h>

MEM_SCOPE mem = sm_create(0);
RNG rng = rng_xor_create(mem)

RANDOM r = rnd_create(mem, rng);

unsigned int x = rnd_int(r);
double d = rnd_real(r);         /* A number between 0.0 and 0.9999999999999. */
int bool = rnd_bool(r)          /* Flip a coin */

Scaling is also possible.

#include <c-craft/rand.h>

MEM_SCOPE mem = sm_create(0);
RNG rng = rng_xor_create(mem)

RANDOM r = rnd_create(mem, rng);

unsigned int x = rnd_scaled_int(r, 1, 7);    /* Throw of the dice */
double d = rnd_scaled_real(r, -273, 0);      /* A random temperature of ice? */

Hashing

One-way Hashing

One way hashing means the original value cannot be directly recovered as the hash may resolve back to multiple values. The addition of a ‘seed’ or ‘salt’ improves security by making it more difficult to reverse engineer.

#include <c-craft/rng.h>

unsigned char data[] = { 0x11, 0x22, 0x33, ... };
int len = ARRAYLEN(data);

unsigned long secret = 0x15162427db35cf07;     /* Seed with a secret value */
unsigned long h = hash_simple(data, len, secret);