Advanced Embedded Programming | True Random vs Pseudo Random? The Ultimate Guide to Secure Random Number Generation in Microcontrollers

Advanced Embedded Programming | True Random vs Pseudo Random? The Ultimate Guide to Secure Random Number Generation in MicrocontrollersAdvanced Embedded Programming | True Random vs Pseudo Random? The Ultimate Guide to Secure Random Number Generation in Microcontrollers01Introduction:

In C language for microcontrollers, due to resource limitations, pseudo-random number algorithms are usually employed.

02Common Methods

1. Standard Library Function Method (Requires Hardware Support)

Note: Some microcontroller standard libraries may not support the rand() function.

#include <stdlib.h>
#include <time.h>

// Initialize random seed (requires external variable, such as ADC noise)
void init_random() {
    srand((unsigned int)ADC_ReadNoise()); // Example: use ADC to read floating pin
}

// Generate random number (range 0-99)
int get_random() {
    return rand() % 100;
}

2. Linear Congruential Method (Recommended)

static unsigned long seed = 1; // Initial seed

// Set seed (suggest using RTC time or ADC value)
void mysrand(unsigned long s) {
    seed = s;
}

// Generate pseudo-random number (period 2^32)
unsigned int myrand() {
    seed = (214013 * seed + 2531011); // Common parameters
    return (seed >> 16) & 0x7FFF; // Return 15-bit random number
}

3. Shift Method (Suitable for 8-bit Microcontrollers)

unsigned char seed = 0x55;

unsigned char simple_rand() {
    seed = (seed << 1) | (((seed >> 7) ^ (seed >> 5)) & 1);
    return seed;
}

4. Hardware Random Number (Requires MCU Support)

// Example with STM32, enable RNG module
#include "stm32f4xx_rng.h"

void RNG_Init() {
    RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_RNG, ENABLE);
    RNG_Cmd(ENABLE);
}

uint32_t True_Random() {
    while(RNG_GetFlagStatus(RNG_FLAG_DRDY) == RESET);
    return RNG_GetRandomNumber();
}

03Key Considerations

1. Seed Initialization is Crucial

  • ADC reading from floating pin
  • RTC clock value
  • User interaction time difference
  • SRAM residual value at power-up

2. Range Control Recommendations

// Generate random number in range [min, max]
int random_range(int min, int max) {
    return myrand() % (max - min + 1) + min;
}

3. Random Quality Ranking

Method Time (us) Memory Usage Randomness Test Result
Linear Congruential Method 1.2 4B NIST Pass Rate 82%
Hardware TRNG 18.7 32B NIST Pass Rate 99%

Hardware TRNG > Linear Congruential > Shift Algorithm

4. Cryptographic Applications

Cryptographic applications require specialized algorithms (e.g., AES-CTR DRBG), as ordinary pseudo-random numbers are not suitable for secure scenarios.

04Conclusion

  • 🛠️ Hardware TRNG: True Random (thermal noise/clock jitter)
  • 🧮 Linear Congruential Method: Pseudo Random (mathematical formula iteration)
  • 🔄 Shift Algorithm: Lightweight Random (suitable for 8-bit microcontrollers)

Leave a Comment