github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/machine/machine_stm32_rng.go (about)

     1  //go:build stm32 && !(stm32f103 || stm32l0x1)
     2  
     3  package machine
     4  
     5  import "device/stm32"
     6  
     7  var rngInitDone = false
     8  
     9  const RNG_MAX_READ_RETRIES = 1000
    10  
    11  // GetRNG returns 32 bits of cryptographically secure random data
    12  func GetRNG() (uint32, error) {
    13  	if !rngInitDone {
    14  		initRNG()
    15  		rngInitDone = true
    16  	}
    17  
    18  	if stm32.RNG.SR.HasBits(stm32.RNG_SR_CECS) {
    19  		return 0, ErrClockRNG
    20  	}
    21  	if stm32.RNG.SR.HasBits(stm32.RNG_SR_SECS) {
    22  		return 0, ErrSeedRNG
    23  	}
    24  
    25  	cnt := RNG_MAX_READ_RETRIES
    26  	for !stm32.RNG.SR.HasBits(stm32.RNG_SR_DRDY) {
    27  		cnt--
    28  		if cnt == 0 {
    29  			return 0, ErrTimeoutRNG
    30  		}
    31  	}
    32  
    33  	ret := stm32.RNG.DR.Get()
    34  	return ret, nil
    35  }