diff --git a/src/crypto/rand/rand_baremetal.go b/src/crypto/rand/rand_baremetal.go index 94b8ad65..7a76498b 100644 --- a/src/crypto/rand/rand_baremetal.go +++ b/src/crypto/rand/rand_baremetal.go @@ -1,5 +1,5 @@ -//go:build stm32wlx || (sam && atsamd51) || (sam && atsame5x) -// +build stm32wlx sam,atsamd51 sam,atsame5x +//go:build stm32wlx || stm32f4 || stm32f7 || stm32l4 || (sam && atsamd51) || (sam && atsame5x) +// +build stm32wlx stm32f4 stm32f7 stm32l4 sam,atsamd51 sam,atsame5x package rand diff --git a/src/machine/machine_stm32_rng.go b/src/machine/machine_stm32_rng.go new file mode 100644 index 00000000..57b27b7a --- /dev/null +++ b/src/machine/machine_stm32_rng.go @@ -0,0 +1,29 @@ +//go:build stm32f4 || stm32f7 || stm32l4 +// +build stm32f4 stm32f7 stm32l4 + +package machine + +import "device/stm32" + +var rngInitDone = false + +const RNG_MAX_READ_RETRIES = 1000 + +// GetRNG returns 32 bits of cryptographically secure random data +func GetRNG() (uint32, error) { + if !rngInitDone { + initRNG() + rngInitDone = true + } + + cnt := RNG_MAX_READ_RETRIES + for !stm32.RNG.SR.HasBits(stm32.RNG_SR_DRDY) { + cnt-- + if cnt == 0 { + return 0, ErrTimeoutRNG + } + } + + ret := stm32.RNG.DR.Get() + return ret, nil +} diff --git a/src/machine/machine_stm32f4.go b/src/machine/machine_stm32f4.go index 652757a3..cc2dc6c1 100644 --- a/src/machine/machine_stm32f4.go +++ b/src/machine/machine_stm32f4.go @@ -1,3 +1,4 @@ +//go:build stm32f4 // +build stm32f4 package machine @@ -586,3 +587,8 @@ const ( ARR_MAX = 0x10000 PSC_MAX = 0x10000 ) + +func initRNG() { + stm32.RCC.AHB2ENR.SetBits(stm32.RCC_AHB2ENR_RNGEN) + stm32.RNG.CR.SetBits(stm32.RNG_CR_RNGEN) +} diff --git a/src/machine/machine_stm32f7.go b/src/machine/machine_stm32f7.go index 76f1007a..838250b5 100644 --- a/src/machine/machine_stm32f7.go +++ b/src/machine/machine_stm32f7.go @@ -1,3 +1,4 @@ +//go:build stm32f7 // +build stm32f7 package machine @@ -716,3 +717,8 @@ const ( ARR_MAX = 0x10000 PSC_MAX = 0x10000 ) + +func initRNG() { + stm32.RCC.AHB2ENR.SetBits(stm32.RCC_AHB2ENR_RNGEN) + stm32.RNG.CR.SetBits(stm32.RNG_CR_RNGEN) +} diff --git a/src/machine/machine_stm32l0.go b/src/machine/machine_stm32l0.go index f2a95e8d..70b7ce58 100644 --- a/src/machine/machine_stm32l0.go +++ b/src/machine/machine_stm32l0.go @@ -1,3 +1,4 @@ +//go:build stm32l0 // +build stm32l0 package machine diff --git a/src/machine/machine_stm32l4.go b/src/machine/machine_stm32l4.go index be58e9b5..2d85bb05 100644 --- a/src/machine/machine_stm32l4.go +++ b/src/machine/machine_stm32l4.go @@ -1,3 +1,4 @@ +//go:build stm32l4 // +build stm32l4 package machine @@ -494,3 +495,12 @@ const ( ARR_MAX = 0x10000 PSC_MAX = 0x10000 ) + +func initRNG() { + stm32.RCC.CRRCR.SetBits(stm32.RCC_CRRCR_HSI48ON) + for !stm32.RCC.CRRCR.HasBits(stm32.RCC_CRRCR_HSI48RDY) { + } + + stm32.RCC.AHB2ENR.SetBits(stm32.RCC_AHB2ENR_RNGEN) + stm32.RNG.CR.SetBits(stm32.RNG_CR_RNGEN) +}