prov_seed.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include "crypto/rand.h"
  10. #include "crypto/rand_pool.h"
  11. #include <openssl/core_dispatch.h>
  12. #include <openssl/err.h>
  13. size_t ossl_rand_get_entropy(ossl_unused const OSSL_CORE_HANDLE *handle,
  14. unsigned char **pout, int entropy,
  15. size_t min_len, size_t max_len)
  16. {
  17. size_t ret = 0;
  18. size_t entropy_available;
  19. RAND_POOL *pool;
  20. pool = ossl_rand_pool_new(entropy, 1, min_len, max_len);
  21. if (pool == NULL) {
  22. ERR_raise(ERR_LIB_RAND, ERR_R_RAND_LIB);
  23. return 0;
  24. }
  25. /* Get entropy by polling system entropy sources. */
  26. entropy_available = ossl_pool_acquire_entropy(pool);
  27. if (entropy_available > 0) {
  28. ret = ossl_rand_pool_length(pool);
  29. *pout = ossl_rand_pool_detach(pool);
  30. }
  31. ossl_rand_pool_free(pool);
  32. return ret;
  33. }
  34. void ossl_rand_cleanup_entropy(ossl_unused const OSSL_CORE_HANDLE *handle,
  35. unsigned char *buf, size_t len)
  36. {
  37. OPENSSL_secure_clear_free(buf, len);
  38. }
  39. size_t ossl_rand_get_nonce(ossl_unused const OSSL_CORE_HANDLE *handle,
  40. unsigned char **pout, size_t min_len, size_t max_len,
  41. const void *salt, size_t salt_len)
  42. {
  43. size_t ret = 0;
  44. RAND_POOL *pool;
  45. pool = ossl_rand_pool_new(0, 0, min_len, max_len);
  46. if (pool == NULL) {
  47. ERR_raise(ERR_LIB_RAND, ERR_R_RAND_LIB);
  48. return 0;
  49. }
  50. if (!ossl_pool_add_nonce_data(pool))
  51. goto err;
  52. if (salt != NULL && !ossl_rand_pool_add(pool, salt, salt_len, 0))
  53. goto err;
  54. ret = ossl_rand_pool_length(pool);
  55. *pout = ossl_rand_pool_detach(pool);
  56. err:
  57. ossl_rand_pool_free(pool);
  58. return ret;
  59. }
  60. void ossl_rand_cleanup_nonce(ossl_unused const OSSL_CORE_HANDLE *handle,
  61. unsigned char *buf, size_t len)
  62. {
  63. OPENSSL_clear_free(buf, len);
  64. }