rand_meth.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright 2011-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 <openssl/evp.h>
  10. #include <openssl/rand.h>
  11. #include "rand_local.h"
  12. /* Implements the default OpenSSL RAND_add() method */
  13. static int drbg_add(const void *buf, int num, double randomness)
  14. {
  15. EVP_RAND_CTX *drbg = RAND_get0_primary(NULL);
  16. if (drbg == NULL || num <= 0)
  17. return 0;
  18. return EVP_RAND_reseed(drbg, 0, NULL, 0, buf, num);
  19. }
  20. /* Implements the default OpenSSL RAND_seed() method */
  21. static int drbg_seed(const void *buf, int num)
  22. {
  23. return drbg_add(buf, num, num);
  24. }
  25. /* Implements the default OpenSSL RAND_status() method */
  26. static int drbg_status(void)
  27. {
  28. EVP_RAND_CTX *drbg = RAND_get0_primary(NULL);
  29. if (drbg == NULL)
  30. return 0;
  31. return EVP_RAND_get_state(drbg) == EVP_RAND_STATE_READY ? 1 : 0;
  32. }
  33. /* Implements the default OpenSSL RAND_bytes() method */
  34. static int drbg_bytes(unsigned char *out, int count)
  35. {
  36. EVP_RAND_CTX *drbg = RAND_get0_public(NULL);
  37. if (drbg == NULL)
  38. return 0;
  39. return EVP_RAND_generate(drbg, out, count, 0, 0, NULL, 0);
  40. }
  41. RAND_METHOD ossl_rand_meth = {
  42. drbg_seed,
  43. drbg_bytes,
  44. NULL,
  45. drbg_add,
  46. drbg_bytes,
  47. drbg_status
  48. };
  49. RAND_METHOD *RAND_OpenSSL(void)
  50. {
  51. return &ossl_rand_meth;
  52. }