hw_rng.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2019-04-25 tyx the first version
  9. */
  10. #include <rtthread.h>
  11. #include <rtdevice.h>
  12. #include <hw_rng.h>
  13. /* Used to save default RNG Context */
  14. static struct rt_hwcrypto_ctx *ctx_default;
  15. /**
  16. * @brief Creating RNG Context
  17. *
  18. * @param device Hardware crypto device
  19. *
  20. * @return RNG context
  21. */
  22. struct rt_hwcrypto_ctx *rt_hwcrypto_rng_create(struct rt_hwcrypto_device *device)
  23. {
  24. struct rt_hwcrypto_ctx *ctx;
  25. ctx = rt_hwcrypto_ctx_create(device, HWCRYPTO_TYPE_RNG, sizeof(struct hwcrypto_rng));
  26. return ctx;
  27. }
  28. /**
  29. * @brief Destroy RNG Context
  30. *
  31. * @param ctx RNG context
  32. */
  33. void rt_hwcrypto_rng_destroy(struct rt_hwcrypto_ctx *ctx)
  34. {
  35. /* Destroy the defaule RNG Context ? */
  36. if (ctx == ctx_default)
  37. {
  38. ctx_default = RT_NULL;
  39. }
  40. rt_hwcrypto_ctx_destroy(ctx);
  41. }
  42. /**
  43. * @brief Setting RNG default devices
  44. *
  45. * @return RT_EOK on success.
  46. */
  47. rt_err_t rt_hwcrypto_rng_default(struct rt_hwcrypto_device *device)
  48. {
  49. struct rt_hwcrypto_ctx *tmp_ctx;
  50. /* if device is null, destroy default RNG Context */
  51. if (device == RT_NULL)
  52. {
  53. if (ctx_default)
  54. {
  55. rt_hwcrypto_rng_destroy(ctx_default);
  56. ctx_default = RT_NULL;
  57. }
  58. return RT_EOK;
  59. }
  60. /* Try create RNG Context */
  61. tmp_ctx = rt_hwcrypto_rng_create(device);
  62. if (tmp_ctx == RT_NULL)
  63. {
  64. return -RT_ERROR;
  65. }
  66. /* create RNG Context success, update default RNG Context */
  67. rt_hwcrypto_rng_destroy(ctx_default);
  68. ctx_default = tmp_ctx;
  69. return RT_EOK;
  70. }
  71. /**
  72. * @brief Getting Random Numbers from RNG Context
  73. *
  74. * @param ctx RNG context
  75. *
  76. * @return Random number
  77. */
  78. rt_uint32_t rt_hwcrypto_rng_update_ctx(struct rt_hwcrypto_ctx *ctx)
  79. {
  80. if (ctx)
  81. {
  82. return ((struct hwcrypto_rng *)ctx)->ops->update((struct hwcrypto_rng *)ctx);
  83. }
  84. return 0;
  85. }
  86. /**
  87. * @brief Return a random number
  88. *
  89. * @return Random number
  90. */
  91. rt_uint32_t rt_hwcrypto_rng_update(void)
  92. {
  93. /* Default device does not exist ? */
  94. if (ctx_default == RT_NULL)
  95. {
  96. /* try create Context from default device */
  97. rt_hwcrypto_rng_default(rt_hwcrypto_dev_default());
  98. }
  99. return rt_hwcrypto_rng_update_ctx(ctx_default);
  100. }