From 2ebaa9f520cc9eb58a4c3271353b83df433891f3 Mon Sep 17 00:00:00 2001 From: deadprogram Date: Tue, 14 Dec 2021 12:17:55 +0100 Subject: [PATCH] machine/samd51: implement TRNG for randomness Signed-off-by: deadprogram --- src/crypto/rand/rand_baremetal.go | 4 ++-- src/machine/machine_atsamd51.go | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/crypto/rand/rand_baremetal.go b/src/crypto/rand/rand_baremetal.go index b5f8bc21..94b8ad65 100644 --- a/src/crypto/rand/rand_baremetal.go +++ b/src/crypto/rand/rand_baremetal.go @@ -1,5 +1,5 @@ -//go:build stm32wlx -// +build stm32wlx +//go:build stm32wlx || (sam && atsamd51) || (sam && atsame5x) +// +build stm32wlx sam,atsamd51 sam,atsame5x package rand diff --git a/src/machine/machine_atsamd51.go b/src/machine/machine_atsamd51.go index 9b678041..ba556c6a 100644 --- a/src/machine/machine_atsamd51.go +++ b/src/machine/machine_atsamd51.go @@ -1,3 +1,4 @@ +//go:build (sam && atsamd51) || (sam && atsame5x) // +build sam,atsamd51 sam,atsame5x // Peripheral abstraction layer for the atsamd51. @@ -2733,3 +2734,20 @@ func syncDAC() { for sam.DAC.SYNCBUSY.HasBits(sam.DAC_SYNCBUSY_DATA0) { } } + +var rngInitDone = false + +// GetRNG returns 32 bits of cryptographically secure random data +func GetRNG() (uint32, error) { + if !rngInitDone { + // Turn on clock for TRNG + sam.MCLK.APBCMASK.SetBits(sam.MCLK_APBCMASK_TRNG_) + + // enable + sam.TRNG.CTRLA.Set(sam.TRNG_CTRLA_ENABLE) + + rngInitDone = true + } + ret := sam.TRNG.DATA.Get() + return ret, nil +}