From 2f423473fc4b132dd6982a22c65d121767550069 Mon Sep 17 00:00:00 2001 From: Benjamin Valentin Date: Tue, 7 Jul 2020 15:34:52 +0200 Subject: [PATCH 1/2] sys/random: add option to use HWRNG as source of randomness Add the `prng_hwrng` module to enable the HWRNG as source of all randomness, not just for seeding a PRNG. saves ~260 bytes compared to using tinymt32. --- Makefile.dep | 4 ++++ sys/include/random.h | 3 +++ sys/random/hwrng.c | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 sys/random/hwrng.c diff --git a/Makefile.dep b/Makefile.dep index 783119f4d3..eb4e8a138d 100644 --- a/Makefile.dep +++ b/Makefile.dep @@ -786,6 +786,10 @@ ifneq (,$(filter random,$(USEMODULE))) USEMODULE += hashes endif + ifneq (,$(filter prng_hwrng,$(USEMODULE))) + FEATURES_REQUIRED += periph_hwrng + endif + ifeq (,$(filter puf_sram,$(USEMODULE))) FEATURES_OPTIONAL += periph_hwrng endif diff --git a/sys/include/random.h b/sys/include/random.h index 252a8379cf..dfd35a15fa 100644 --- a/sys/include/random.h +++ b/sys/include/random.h @@ -22,6 +22,9 @@ * - Simple Park-Miller PRNG * - Musl C PRNG * - Fortuna (CS)PRNG + * - Hardware Random Number Generator (non-seedable) + * HWRNG differ in how they generate random numbers and may not use a PRNG internally. + * Refer to the manual of your MCU for details. */ #ifndef RANDOM_H diff --git a/sys/random/hwrng.c b/sys/random/hwrng.c new file mode 100644 index 0000000000..8bde81b68c --- /dev/null +++ b/sys/random/hwrng.c @@ -0,0 +1,38 @@ +/** + * Copyright (C) 2020 ML!PA Consulting GmbH + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + + /** + * @ingroup sys_random + * @{ + * @file + * + * @brief Use the HWRNG as source of randomness + * + * @author Benjamin Valentin + * @} + */ + +#include "kernel_defines.h" +#include "periph/hwrng.h" +#include "random.h" + +uint32_t random_uint32(void) +{ + uint32_t rnd; + hwrng_read(&rnd, sizeof(rnd)); + return rnd; +} + +void random_init(uint32_t val) +{ + (void) val; + + if (!IS_ACTIVE(MODULE_PERIPH_INIT_HWRNG)) { + hwrng_init(); + } +} From 04f3a9798c2dc9b07f7f7699a7d46a23292e2472 Mon Sep 17 00:00:00 2001 From: Benjamin Valentin Date: Wed, 8 Jul 2020 18:27:00 +0200 Subject: [PATCH 2/2] tests/rng: print when HWRNG is uses as system RNG --- tests/rng/test.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/rng/test.c b/tests/rng/test.c index 41bf6f229e..29521c715a 100644 --- a/tests/rng/test.c +++ b/tests/rng/test.c @@ -65,6 +65,8 @@ static void test_init(char *name) puts("Tiny Mersenne Twister PRNG.\n"); #elif MODULE_PRNG_XORSHIFT puts("XOR Shift PRNG.\n"); +#elif MODULE_PRNG_HWRNG + puts("Hardware RNG.\n"); #else puts("unknown PRNG.\n"); #endif