Wiznet makers

ronpang

Published July 08, 2025 © Apache License 2.0 (Apache-2.0)

130 UCC

51 WCC

32 VAR

0 Contests

1 Followers

0 Following

Chapter 34: W55MH32’s TRNG - True Random Number Generator

Chapter 34: W55MH32’s TRNG - True Random Number Generator

COMPONENTS
PROJECT DESCRIPTION

Chapter 34: W55MH32’s TRNG - True Random Number Generator

In the current digital era, information security has become a crucial factor that cannot be ignored in the design of embedded systems. From the identity authentication of IoT devices to the generation of encryption keys for communication, high-quality random numbers are the cornerstone for building a secure system. The built-in True Random Number Generator (TRNG) module of W55MH32 provides developers with a hardware-level solution for random numbers.

This article will explain true random numbers from aspects such as the working principle, application scenarios, and program design of the W55MH32 TRNG.

TRNG Overview

Introduction

TRNG (True Random Number Generator) is a true random number generator, which is different from PRNG (Pseudo Random Number Generator). Its randomness comes from physical noise rather than deterministic algorithms. The TRNG module of W55MH32 utilizes the internal physical noise sources of the chip (such as thermal noise, clock jitter, etc.) to generate unpredictable random numbers. It is suitable for scenarios that require high randomness, such as encryption, security authentication, and random key generation.

 

Hardware Structure

The TRNG module of W55MH32 is mainly composed of the following parts:

  • The TRNG module of W55MH32 is mainly composed of the following components:
  • Noise source: Usually based on the thermal noise of MOS transistors or the jitter of ring oscillators, it generates the original random signal.
  • Amplification and shaping circuit: Enhances the noise signal and converts it into a manageable digital signal.
  • Sampling circuit: Samples the noise signal to generate the original random bit stream.
  • Entropy accumulator: Collects the entropy obtained from sampling and accumulates sufficient randomness.
  • Random number generator: Converts the accumulated entropy into usable random numbers (such as 32-bit integers).
  • Hardware testing and calibration: Ensures the normal operation of the noise source, and calibrates it if necessary.

The Difference Between True Randomness and Pseudo-Randomness

 

Random numbers in computer science are mainly divided into two categories - true randomness and pseudo-randomness. The comparison is as follows:

Characteristic

TrueRandom Number Generator (TRNG)

Pseudo Random Number Generator (PRNG)

Randomness Source

Physical noise (thermal noise, clock jitter)

Mathematical algorithms (such as linear congruential method)

Predictability

Unpredictable (based on physical phenomena)

Theoretically predictable (given the seed and algorithm)

Periodicity

No periodicity

Has periodicity (the period length depends on the algorithm)

Hardware Dependence

Requires specific hardware modules

Purely software - implemented

Application Scenarios

Encryption,security authentication, cryptography

Simulation, games, random numbers for non - security scenarios

 

 

Workflow

The workflow of TRNG can be divided into the following key steps:

(1) Noise acquisition stage: Multiple ring oscillators operate simultaneously, and the minute differences in their output frequencies are captured and amplified. These differences are input as the original random signal to the subsequent processing circuit.

(2) Digitalization stage: The analog random signal is sampled and converted into a digital bit stream. The sampling process is typically carried out using a high-speed clock to ensure the capture of sufficient random information.

(3) Randomness enhancement stage: The original digital signal may have statistical deviations, which need to be post-processed through algorithms. The TRNG of W55MH32 uses a structure called an "exclusive OR tree", performing exclusive OR operations on the outputs of multiple ring oscillators to enhance randomness and eliminate possible deviations.

(4) Quality detection stage: The generated random numbers undergo real-time statistical tests to ensure they meet the randomness standards. The TRNG of W55MH32 implements two main tests:

a) Single-bit frequency test: Ensuring the probability of 0 and 1 occurrences is close to 50%

b) Run-length test: Detecting whether the length of consecutive identical bits conforms to a random distribution

(5) Output stage: The random numbers that pass the quality detection are stored in the data register and made available for CPU reading. When a quality issue is detected, the TRNG automatically disables the output and sets an error flag.

 

Application Scenarios

  • Encryption key generation: Generate initial keys for encryption algorithms such as AES and RSA.
  • Security authentication: Generate random challenge values (Challenge) for identity verification.
  • Random number seed: Provide high-quality initial seeds for PRNG.
  • Security protocols: Such as TLS handshake, VPN key negotiation, etc.
  • Games: Applications requiring high randomness such as virtual dice, cards, etc.

 

Notes

(1) Low power mode: In sleep or shutdown mode, the TRNG may cease to function and needs to be reinitialized.

(2) Noise source dependence: Environmental factors such as temperature and voltage may affect the intensity of the noise source, resulting in random fluctuations.

(3) Verification test: In critical applications, it is recommended to conduct offline tests on the generated random numbers (such as using NIST test tools).

(4) Multi-thread safety: In the RTOS environment, when accessing the TRNG, locking should be applied to avoid race conditions.

Program Design

TRNG_IntTest Routine

The TRNG_IntTest routine mainly implements the interrupt testing function of the true random number generator (TRNG) based on the W55MH32 chip. The following is the implementation process and result verification:

Execute the function TRNG_Int()

The interrupt configuration of TRNG, the enable of TRNG output, the enable of interrupts, the setting of random seeds and the startup of TRNG hardware are mainly implemented in the TRNG_Int() function:

void TRNG_Int(void)
{
    NVIC_Configuration();
    TRNG_Out(ENABLE);
    TRNG_ITConfig(ENABLE);
    TRNG_SetPseudoRandom(0X12345560);
    TRNG_Start();
}

 

 

Configure the Nested Vector Interrupt Controller

NVIC_Configuration() is the interrupt configuration function:

void NVIC_Configuration(void)
{
    NVIC_InitTypeDef NVIC_InitStructure;
 
    NVIC_SetPriorityGrouping(NVIC_PriorityGroup_1);
 
    NVIC_InitStructure.NVIC_IRQChannel                   = TRNG_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority        = 1;
    NVIC_InitStructure.NVIC_IRQChannelCmd                = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
}

 

This function mainly includes the following configurations:

  • NVIC_PriorityGroup_1: Indicates the use of priority group mode 1, which is as follows:
    • Preemption priority occupies 1 bit (0-1)
    • Subpriority occupies 3 bits (0-7)
  • Interrupt parameter configuration:
    • Interrupt source: TRNG_IRQn (True Random Number Generator interrupt)
    • Dual priority mechanism: The preemption priority 1 can interrupt an interrupt with a lower preemption priority
    • Subpriority 1: Determines the response order when the preemption priorities are the same
    • Enable the TRNG hardware interrupt channel
  • NVIC initialization

 

Enable TRNG output function

The TRNG_Out() function is a crucial step in the TRNG initialization process. By controlling the clock, it enables or disables the TRNG module, thereby indirectly controlling the generation of random numbers.

void TRNG_Out(FunctionalState NewState)
{
          if (NewState != DISABLE)
          {
                    RCC->RCC_SYSCFG_CONFIG = 0x01;
                    SYSCFG->SYSCFG_LOCK = 0xCDED3526;
                    SYSCFG->SSC_CLK_EN |= TRNG_RNG_ENABLE;
          }
          else
          {
                    RCC->RCC_SYSCFG_CONFIG = 0x00;
                    SYSCFG->SSC_CLK_EN &= ~TRNG_RNG_ENABLE;
          }
}
 

When enabling the TRNG output, first configure the system clock domain (RCC_SYSCFG_CONFIG = 0x01), then write a specific key to the lock register (SYSCFG_LOCK = 0xCDED3526) to unlock the SYSCFG register, and finally set the corresponding bit of the security system clock enable register (SSC_CLK_EN) to enable the TRNG clock.

When disabling the output, perform the opposite operation: clear the clock domain configuration and disable the TRNG clock. This design indirectly manages the TRNG module through clock control and is a common practice in low-power and security designs. The locking mechanism can prevent accidental modification of the registers.

 

Enable TRNG Interrupt

TRNG_ITConfig() is a function that controls the TRNG interrupt function, and is mainly used to enable or disable the interrupt mechanism of the TRNG module:

void TRNG_ITConfig(FunctionalState NewState)
{
          if (NewState != DISABLE)
          {
                    TRNG->RNG_CSR |= TRNG_RNG_CSR_INTP_EN_Mask;
          }
          else
          {
                    TRNG->RNG_CSR &= ~TRNG_RNG_CSR_INTP_EN_Mask;
          }
}

 

When the input parameter is "ENABLE" to enable the interrupt, the function uses bitwise operation (|=) to set the interrupt enable bit (TRNG_RNG_CSR_INTP_EN_Mask) in the TRNG control status register (RNG_CSR) to 1, allowing TRNG to trigger an interrupt when the random number generation is completed or an error is detected.

When the input parameter is "DISABLE" to disable the interrupt, it uses bitwise operation (&= ~) to clear this bit, disabling the interrupt function.

Set the pseudo-random number seed

The pseudo-random seed can be set through the TRNG_SetPseudoRandom() function, which is mainly used to enhance the quality of random number generation or to achieve specific application scenarios:

void TRNG_SetPseudoRandom(uint32_t TRNG_PseudoRandom)
{
          TRNG->RNG_PN = TRNG_PseudoRandom;
}

 

This function writes the 32-bit seed value passed in to the RNG_PN register.

 

Activate the TRNG hardware

The TRNG_Start() function is used to start the TRNG (True Random Number Generator). It activates the TRNG module by configuring specific registers.

void TRNG_Start(void)
{
          TRNG->RNG_AMA &= ~TRNG_RNG_AMA_PD_ALL_Mask;
          TRNG->RNG_CSR &= ~TRNG_RNG_CSR_S128_TRNG0_Mask;
}

 

The function first clears the power-off bit through TRNG->RNG_AMA &= ~TRNG_RNG_AMA_PD_ALL_Mask, waking up the analog circuit of TRNG from the low-power mode and activating the ring oscillator and other physical random sources. Then, it clears the 128-bit sampling mode flag through TRNG->RNG_CSR &= ~TRNG_RNG_CSR_S128_TRNG0_Mask. These two steps jointly complete the initialization of TRNG, preparing for the subsequent generation of random numbers.

 

Interrupt Service Function

The function RNG_IRQHandler() is responsible for handling the TRNG interrupt, and it is mainly used to respond to the completion event of random number generation and detect security attack events:

void RNG_IRQHandler(void)
{
    if (TRNG_GetITStatus(TRNG_IT_RNG0_S128) == SET)
    {
        printf("Rng : %08X %08X %08X %08X \r\n", TRNG->RNG_DATA, TRNG->RNG_DATA, TRNG->RNG_DATA, TRNG->RNG_DATA);
        TRNG_ClearITPendingBit(TRNG_IT_RNG0_S128);
    }
    if (TRNG_GetITStatus(TRNG_IT_RNG0_ATTACK) == SET)
    {
        TRNG_ClearITPendingBit(TRNG_IT_RNG0_ATTACK);
    }
    NVIC_ClearPendingIRQ(TRNG_IRQn);
}

 

When the 128-bit random number generation is completed (with the TRNG_IT_RNG0_S128 flag set), the function reads the RNG_DATA register four times consecutively to obtain 128-bit random numbers (4 32-bit values) and prints them out. Then, it clears the interrupt flag; when a security attack is detected (with the TRNG_IT_RNG0_ATTACK flag set), it also clears the interrupt flag. Finally, the function clears the NVIC interrupt suspension flag to allow subsequent interrupts.

 

Main Function main()

The main function main() is as follows:

int main(void)
{
    RCC_ClocksTypeDef clocks;
 
    delay_init();
 
    UART_Configuration(115200);
    printf("TRNG Int Out Test.\n");
    RCC_GetClocksFreq(&clocks);
 
    printf("SYSCLK: %3.1fMhz, HCLK: %3.1fMhz, PCLK1: %3.1fMhz, PCLK2: %3.1fMhz, ADCCLK: %3.1fMhz\n",
           (float)clocks.SYSCLK_Frequency / 1000000, (float)clocks.HCLK_Frequency / 1000000,
           (float)clocks.PCLK1_Frequency / 1000000, (float)clocks.PCLK2_Frequency / 1000000, (float)clocks.ADCCLK_Frequency / 1000000);
 
 
    TRNG_Int();
    while (1);
}
 

The program first initializes the delay function and configures the serial communication (with a baud rate of 115200), then prints out the frequencies of all system clocks (SYSCLK, HCLK, PCLK1/2, ADCCLK). Next, it calls the TRNG_Int() function to initialize TRNG. This function configures the NVIC interrupt, enables the TRNG output, sets the interrupt mode and the pseudo-random seed, and starts TRNG. Finally, the program enters an infinite loop, waiting for TRNG to generate a 128-bit random number that triggers an interrupt. The interrupt handling function RNG_IRQHandler() reads and prints the random number.

Download Verification

After the program was downloaded and run, it first printed the name of the example and the frequencies of each clock in the system. Then, it continuously printed the generated random numbers:

 

TRNG_PollingTest Routine

The TRNG_PollingTest routine is for the polling mode operation of the TRNG (True Random Number Generator). It is different from the previous interrupt mode. This function obtains random numbers through an active query approach.

Execute the function TRNG_Polling()

The functions for enabling, starting and querying the output of TRNG, as well as for printing, are mainly implemented in the TRNG_Polling() function:

void TRNG_Polling(void)
{
    uint32_t Buf[4];
    TRNG_Out(ENABLE);
    TRNG_Start();
    while (1)
    {
        if (0 == TRNG_Get(Buf))
        {
            printf("Rng : %08X %08X %08X %08X \r\n", Buf[0], Buf[1], Buf[2], Buf[3]);
            TRNG_ClearITPendingBit(TRNG_IT_RNG0_S128);
        }
    }
}

 

First, a 4-element 32-bit integer array was defined as the buffer. Then, TRNG_Out(ENABLE) was called to enable the TRNG output, and TRNG_Start() was used to start the TRNG to generate random numbers. Subsequently, an infinite loop was entered, and the TRNG_Get() function was repeatedly called to attempt to obtain random numbers. When the function returned 0, it indicated a successful acquisition. At this point, the 4 32-bit random numbers were printed and output, and the interrupt flag was cleared (even in the polling mode, it is necessary to clear it). 

The TRNG_Start() and TRNG_Get() functions have been explained in the previous section, and the main function only has the names of the functions modified and the execution functions remain the same. Therefore, there is no need to elaborate on it here.

  1. Download Verification

After the program was downloaded and run, it first printed the name of the example and the frequencies of each system clock. Then, it continuously printed the generated random numbers:

Summary

The TRNG module of W55MH32 provides the hardware-level true random number generation capability for embedded systems, and is an important component for building secure systems. Through proper configuration and usage, it can generate high-quality random numbers, meeting the requirements of security-sensitive applications such as encryption and authentication.

 

WIZnet is an independent semiconductor company founded in 1998. Its products include the Internet processor iMCU™, which adopts TOE (TCP/IP offloading engine) technology and is based on a unique patented fully hardwired TCP/IP. iMCU™ is designed for embedded Internet devices in various applications.

WIZnet has over 70 distributors worldwide, with offices in Hong Kong, South Korea, and the United States, providing technical support and product marketing.

The region managed by the Hong Kong office includes: Australia, India, Turkey, and Asia (excluding South Korea and Japan).

Documents
Comments Write