Skip to content

Commit f68e722

Browse files
committed
stm32/rng: Use Yasmarang for rng_get() if MCU doesn't have HW RNG.
1 parent cda9641 commit f68e722

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

ports/stm32/rng.c

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,30 @@ STATIC mp_obj_t pyb_rng_get(void) {
6060
}
6161
MP_DEFINE_CONST_FUN_OBJ_0(pyb_rng_get_obj, pyb_rng_get);
6262

63+
#else // MICROPY_HW_ENABLE_RNG
64+
65+
// For MCUs that don't have an RNG we still need to provide a rng_get() function,
66+
// eg for lwIP. A pseudo-RNG is not really ideal but we go with it for now. We
67+
// don't want to use urandom's pRNG because then the user won't see a reproducible
68+
// random stream.
69+
70+
// Yasmarang random number generator by Ilya Levin
71+
// http://www.literatecode.com/yasmarang
72+
STATIC uint32_t pyb_rng_yasmarang(void) {
73+
static uint32_t pad = 0xeda4baba, n = 69, d = 233;
74+
static uint8_t dat = 0;
75+
76+
pad += dat + d * n;
77+
pad = (pad << 3) + (pad >> 29);
78+
n = pad | 2;
79+
d ^= (pad << 31) + (pad >> 1);
80+
dat ^= (char)pad ^ (d >> 8) ^ 1;
81+
82+
return pad ^ (d << 5) ^ (pad >> 18) ^ (dat << 1);
83+
}
84+
85+
uint32_t rng_get(void) {
86+
return pyb_rng_yasmarang();
87+
}
88+
6389
#endif // MICROPY_HW_ENABLE_RNG

0 commit comments

Comments
 (0)