furi_hal_random.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. ;
  10. LL_RNG_Enable(RNG);
  11. while(!LL_RNG_IsActiveFlag_DRDY(RNG))
  12. ;
  13. if((LL_RNG_IsActiveFlag_CECS(RNG)) || (LL_RNG_IsActiveFlag_SECS(RNG))) {
  14. furi_crash("TRNG error");
  15. }
  16. uint32_t random_val = LL_RNG_ReadRandData32(RNG);
  17. LL_RNG_Disable(RNG);
  18. LL_HSEM_ReleaseLock(HSEM, CFG_HW_RNG_SEMID, 0);
  19. return random_val;
  20. }
  21. void furi_hal_random_fill_buf(uint8_t* buf, uint32_t len) {
  22. while(LL_HSEM_1StepLock(HSEM, CFG_HW_RNG_SEMID))
  23. ;
  24. LL_RNG_Enable(RNG);
  25. for(uint32_t i = 0; i < len; i += 4) {
  26. while(!LL_RNG_IsActiveFlag_DRDY(RNG))
  27. ;
  28. if((LL_RNG_IsActiveFlag_CECS(RNG)) || (LL_RNG_IsActiveFlag_SECS(RNG))) {
  29. furi_crash("TRNG error");
  30. }
  31. uint32_t random_val = LL_RNG_ReadRandData32(RNG);
  32. uint8_t len_cur = ((i + 4) < len) ? (4) : (len - i);
  33. memcpy(&buf[i], &random_val, len_cur);
  34. }
  35. LL_RNG_Disable(RNG);
  36. LL_HSEM_ReleaseLock(HSEM, CFG_HW_RNG_SEMID, 0);
  37. }
  38. void srand(unsigned seed) {
  39. }
  40. int rand() {
  41. return (furi_hal_random_get() & RAND_MAX);
  42. }