summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDamien George <damien@micropython.org>2020-10-20 14:17:46 +1100
committerDamien George <damien@micropython.org>2020-10-29 14:14:40 +1100
commit3e455e9792b5851a21ed2d94d518b21557d2a361 (patch)
tree515e66eb272d5819e36b6752da5f173ef4c8f5b6
parent59019d7f759c78dedd8d353d24c8d64a7a9981c7 (diff)
stm32/rng: Use SysTick+RTC+unique-id to seed pRNG for MCUs without RNG.
The same seed will only occur if the board is the same, the RTC has the same time (eg freshly powered up) and the first call to this function (eg via an "import random") is done at exactly the same time since reset. Signed-off-by: Damien George <damien@micropython.org>
-rw-r--r--ports/stm32/rng.c15
1 files changed, 13 insertions, 2 deletions
diff --git a/ports/stm32/rng.c b/ports/stm32/rng.c
index b23941998..eea02f726 100644
--- a/ports/stm32/rng.c
+++ b/ports/stm32/rng.c
@@ -24,6 +24,7 @@
* THE SOFTWARE.
*/
+#include "rtc.h"
#include "rng.h"
#if MICROPY_HW_ENABLE_RNG
@@ -63,16 +64,26 @@ MP_DEFINE_CONST_FUN_OBJ_0(pyb_rng_get_obj, pyb_rng_get);
#else // MICROPY_HW_ENABLE_RNG
// For MCUs that don't have an RNG we still need to provide a rng_get() function,
-// eg for lwIP. A pseudo-RNG is not really ideal but we go with it for now. We
+// eg for lwIP and random.seed(). A pseudo-RNG is not really ideal but we go with
+// it for now, seeding with numbers which will be somewhat different each time. We
// don't want to use urandom's pRNG because then the user won't see a reproducible
// random stream.
// Yasmarang random number generator by Ilya Levin
// http://www.literatecode.com/yasmarang
STATIC uint32_t pyb_rng_yasmarang(void) {
- static uint32_t pad = 0xeda4baba, n = 69, d = 233;
+ static bool seeded = false;
+ static uint32_t pad = 0, n = 0, d = 0;
static uint8_t dat = 0;
+ if (!seeded) {
+ seeded = true;
+ rtc_init_finalise();
+ pad = *(uint32_t *)MP_HAL_UNIQUE_ID_ADDRESS ^ SysTick->VAL;
+ n = RTC->TR;
+ d = RTC->SSR;
+ }
+
pad += dat + d * n;
pad = (pad << 3) + (pad >> 29);
n = pad | 2;