furi-hal-random.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "furi-hal-random.h"
  2. #include <furi.h>
  3. #include <furi-hal.h>
  4. #include <stm32wbxx_ll_rng.h>
  5. #include <stm32wbxx_ll_hsem.h>
  6. #include <hw_conf.h>
  7. uint32_t furi_hal_random_get() {
  8. while( LL_HSEM_1StepLock(HSEM, CFG_HW_RNG_SEMID));
  9. LL_RNG_Enable(RNG);
  10. while (!LL_RNG_IsActiveFlag_DRDY(RNG));
  11. if ((LL_RNG_IsActiveFlag_CECS(RNG)) || (LL_RNG_IsActiveFlag_SECS(RNG))) {
  12. furi_crash("TRNG error");
  13. }
  14. uint32_t random_val = LL_RNG_ReadRandData32(RNG);
  15. LL_RNG_Disable(RNG);
  16. LL_HSEM_ReleaseLock(HSEM, CFG_HW_RNG_SEMID, 0);
  17. return random_val;
  18. }
  19. void furi_hal_random_fill_buf(uint8_t* buf, uint32_t len) {
  20. while( LL_HSEM_1StepLock(HSEM, CFG_HW_RNG_SEMID));
  21. LL_RNG_Enable(RNG);
  22. for (uint32_t i = 0; i < len; i+= 4) {
  23. while (!LL_RNG_IsActiveFlag_DRDY(RNG));
  24. if ((LL_RNG_IsActiveFlag_CECS(RNG)) || (LL_RNG_IsActiveFlag_SECS(RNG))) {
  25. furi_crash("TRNG error");
  26. }
  27. uint32_t random_val = LL_RNG_ReadRandData32(RNG);
  28. uint8_t len_cur = ((i+4) < len) ? (4) : (len-i);
  29. memcpy(&buf[i], &random_val, len_cur);
  30. }
  31. LL_RNG_Disable(RNG);
  32. LL_HSEM_ReleaseLock(HSEM, CFG_HW_RNG_SEMID, 0);
  33. }
  34. void srand(unsigned seed) {
  35. }
  36. int rand() {
  37. return (furi_hal_random_get() & RAND_MAX);
  38. }