Portable crypto-safe rand library in C


Leah Rowe

Return to index

Article published by: Leah Rowe

Date of publication: 4 December 2026

C programmers using rand piss me off. They always do it wrong.

Everyone does it wrong. I therefore release this proof of concept as a public service, under the public domain (via CC-0 SPDX header).

Here I will show you how to do it right. This uses portable assumptions, with arc4 or getrandom depending on the OS, and a fallback to /dev/urandom. I want everyone to do randomisierung properly, so I release this to the public domain or CC-0.

Note that “portable” means: Linux, BSD, MAC OS, etc. I don’t care about Windows users. Unix is the only one for me.

The example below is a full program, but you can adapt this as you please.

Here is a Makefile:

# SPDX-License-Identifier: CC0-1.0
# SPDX-FileCopyrightText: 2026 Leah Rowe <leah@libreboot.org>

CC?=cc
CFLAGS?=-Os -Wall -Wextra -std=c99
DESTDIR?=
PREFIX?=/usr/local
INSTALL?=install

rand: rand.c
	$(CC) $(CFLAGS) rand.c -o rand

install:
	$(INSTALL) rand $(DESTDIR)$(PREFIX)/bin/rand

uninstall:
	rm -f $(DESTDIR)$(PREFIX)/bin/rand

distclean:
	rm -f rand

clean:
	rm -f rand

and here is rand.c which you can adapt as you please:

/* SPDX-License-Identifier: CC0-1.0                                    ( >:3 )
   Copyright (c) 2026 Leah Rowe <leah@libreboot.org>                    /| |\
                                                                         / \
   Proof of concept. Generate random numbers, the right way.                 */

#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L
#endif

#ifndef _FILE_OFFSET_BITS
#define _FILE_OFFSET_BITS 64
#endif

#if defined(__linux__)
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1 /* needed for linux syscall */
#endif
#include <sys/syscall.h> /* for getrandom syscall */
#else
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1 /* bsd arc4random_buf */
#endif
#endif

#ifdef __OpenBSD__
#include <sys/param.h>
#endif

#include <sys/types.h>

#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>

int
rsize(size_t *val, size_t n);

int
rset(void *buf, size_t n);

int
main(int argc, char *argv[])
{
	size_t part_size;

	(void) argc, (void) argv;

#ifdef __OpenBSD__
	if (pledge("stdio", NULL) == -1)
		err(EXIT_FAILURE, "pledge");
#endif

	/* PoC. change 29 to whatever
	 */
	if (rsize(&part_size, 29) < 0)
		err(EXIT_FAILURE, "rand");

	printf("%zu\n", part_size);

	return 0;
}

/* random number within size n
 * with modulo bias rejection sampling
 */
int
rsize(size_t *val, size_t n)
{
	int r = 0;
	size_t rval;
	size_t max;
	if (!n || !val) {
		errno = EINVAL;
		return -1;
	}

	max = (n == 1)
	    ? SIZE_MAX : (SIZE_MAX - ((SIZE_MAX - n + 1) % n));

	/* rejection sampling (clamp rand to eliminate modulo bias) */
	while ((r = rset(&rval, sizeof(rval))) != -1 &&
	    rval > max);

	if (r == -1)
		return -1;

	*val = rval % n;
	return 0;
}

/* fill buffer with random numbers
 */
int
rset(void *buf, size_t n)
{
#if(!(defined(__OpenBSD__) || defined(__FreeBSD__) || \
    defined(__NetBSD__) || defined(__APPLE__) || \
    defined(__DragonFly__)))
	char *abuf;
	int fd = -1;
	ssize_t uval;
	ssize_t off = 0;
#if defined(__linux__) && defined(SYS_getrandom)
	long rval;
#endif
#endif

	if (!n || !buf) {
		errno = EINVAL;
		return -1;
	}

	if (n >= SSIZE_MAX) {
		errno = EOVERFLOW;
		return -1;
	}

#if((defined(__OpenBSD__) || defined(__FreeBSD__) || \
    defined(__NetBSD__) || defined(__APPLE__) || \
    defined(__DragonFly__)))

	/* WARNING: arc4 aborts (it's a void) on failure,
	 *          but such failures are extremely rare.
	 *	    Keep note if using this in a library (on BSD).
	 */
	arc4random_buf(buf, n);

#else
	abuf = (char *) buf;

/* Even modern kernels may not have getrandom
 * in restrictive container environments. We
 * also want to support older Linux kernels.
 */
#if defined(__linux__) && defined(SYS_getrandom)
	while (1) {
		/* Direct syscall used, for granular control
		 * and maximum libc compatibility, including legacy glibc.
		 */
		while ((rval = syscall(SYS_getrandom, abuf + off,
		    n - (size_t) off, 0)) < 0 && errno == EINTR);

		/* Errors are irrelevant here; break out and continue
		 * from the current offset with /dev/urandom fallback
		 */
		if (!rval || rval < 0)
			break;

		if ((off += (ssize_t) rval) == (ssize_t) n)
			return 0;
	}

	/* ENOSYS for instance, if getrandom isn't in your kernel build.
	 */

#endif
	/* /dev/urandom fallback
	 */
	while((fd = open("/dev/urandom", O_RDONLY)) < 0
	    && errno == EINTR);

	if (fd == -1)
		while((fd = open("/dev/random", O_RDONLY)) < 0
		    && errno == EINTR);

	if (fd == -1)
		return -1;

	while (1) {
		while((uval = read(fd, abuf + off,
		    n - (size_t) off)) < 0 && errno == EINTR);

		if (!uval || uval <= 0) {
			(void) close(fd);
			return -1;
		}

		if ((off += uval) == (ssize_t ) n)
			break;
	}

	(void) close(fd); /* rand must not fail. ignore close err. */
#endif
	return 0;
}

Markdown file for this page: https://vimuser.org/rand.md

Site map

This HTML page was generated by the Libreboot Static Site Generator.