luat_crypto_air101.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "string.h"
  2. #include "wm_include.h"
  3. #include "wm_crypto_hard.h"
  4. #include "aes.h"
  5. #include "wm_osal.h"
  6. #include "wm_regs.h"
  7. #include "wm_debug.h"
  8. #include "wm_crypto_hard.h"
  9. #include "wm_internal_flash.h"
  10. #include "wm_pmu.h"
  11. #include "luat_base.h"
  12. #include "luat_crypto.h"
  13. #define LUAT_LOG_TAG "crypto"
  14. #include "luat_log.h"
  15. #include "FreeRTOS.h"
  16. #include "task.h"
  17. static unsigned char trng_wait;
  18. static unsigned char trng_pool[24];
  19. void rngGenRandom() {
  20. uint32_t ret;
  21. tls_crypto_random_init(tls_os_get_time(), CRYPTO_RNG_SWITCH_32);
  22. vTaskDelay(1);
  23. for (size_t i = 0; i < sizeof(trng_pool) / sizeof(uint32_t); i++)
  24. {
  25. tls_reg_read32(HR_CRYPTO_SEC_CFG);
  26. ret = tls_reg_read32(HR_CRYPTO_RNG_RESULT);
  27. memcpy(trng_pool + i * sizeof(uint32_t), &ret, sizeof(uint32_t));
  28. }
  29. tls_crypto_random_stop();
  30. }
  31. int luat_crypto_trng(char* buff, size_t len) {
  32. char* dst = buff;
  33. while (len > 0) {
  34. // 池内没有剩余的随机值? 生成一次
  35. if (trng_wait == 0) {
  36. // LLOGD("生成一次随机数 24字节,放入池中");
  37. rngGenRandom();
  38. trng_wait = 24;
  39. }
  40. // 剩余随机值够用, 直接拷贝
  41. if (len <= trng_wait) {
  42. memcpy(dst, trng_pool + (24 - trng_wait), len);
  43. trng_wait -= len;
  44. return 0;
  45. }
  46. // 不够用, 先把现有的用完, 然后下一个循环
  47. memcpy(dst, trng_pool + (24 - trng_wait), trng_wait);
  48. dst += trng_wait;
  49. len -= trng_wait;
  50. trng_wait = 0;
  51. }
  52. return 0;
  53. }