stm32.h 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Use hardware RNG peripheral
  2. // Working with HAL, LL Driver (untested)
  3. #ifdef STM32F4
  4. #include "stm32f4xx.h"
  5. static int
  6. hydro_random_init(void)
  7. {
  8. const char ctx[hydro_hash_CONTEXTBYTES] = { 'h', 'y', 'd', 'r', 'o', 'P', 'R', 'G' };
  9. hydro_hash_state st;
  10. uint16_t ebits = 0;
  11. __IO uint32_t tmpreg;
  12. // Enable RNG clock source
  13. SET_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);
  14. // Delay after an RCC peripheral clock enabling
  15. tmpreg = READ_BIT(RCC->AHB2ENR, RCC_AHB2ENR_RNGEN);
  16. UNUSED(tmpreg);
  17. // RNG Peripheral enable
  18. SET_BIT(RNG->CR, RNG_CR_RNGEN);
  19. hydro_hash_init(&st, ctx, NULL);
  20. while (ebits < 256) {
  21. while (!(READ_BIT(RNG->SR, RNG_SR_DRDY))) {
  22. }
  23. uint32_t r = RNG->DR;
  24. hydro_hash_update(&st, (const uint32_t*) &r, sizeof r);
  25. ebits += 32;
  26. }
  27. hydro_hash_final(&st, hydro_random_context.state, sizeof hydro_random_context.state);
  28. hydro_random_context.counter = ~LOAD64_LE(hydro_random_context.state);
  29. return 0;
  30. }
  31. #else
  32. # error SMT32 implementation missing!
  33. #endif