nsRandomGenerator.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. #include "nsRandomGenerator.h"
  5. #include "ScopedNSSTypes.h"
  6. #include "nsNSSComponent.h"
  7. #include "pk11pub.h"
  8. #include "prerror.h"
  9. #include "secerr.h"
  10. NS_IMPL_ISUPPORTS(nsRandomGenerator, nsIRandomGenerator)
  11. NS_IMETHODIMP
  12. nsRandomGenerator::GenerateRandomBytes(uint32_t aLength,
  13. uint8_t** aBuffer)
  14. {
  15. NS_ENSURE_ARG_POINTER(aBuffer);
  16. *aBuffer = nullptr;
  17. nsNSSShutDownPreventionLock locker;
  18. if (isAlreadyShutDown()) {
  19. return NS_ERROR_NOT_AVAILABLE;
  20. }
  21. mozilla::UniquePK11SlotInfo slot(PK11_GetInternalSlot());
  22. if (!slot) {
  23. return NS_ERROR_FAILURE;
  24. }
  25. auto buf = static_cast<uint8_t*>(moz_xmalloc(aLength));
  26. if (!buf) {
  27. return NS_ERROR_OUT_OF_MEMORY;
  28. }
  29. SECStatus srv = PK11_GenerateRandomOnSlot(slot.get(), buf, aLength);
  30. if (srv != SECSuccess) {
  31. free(buf);
  32. return NS_ERROR_FAILURE;
  33. }
  34. *aBuffer = buf;
  35. return NS_OK;
  36. }
  37. nsRandomGenerator::~nsRandomGenerator()
  38. {
  39. nsNSSShutDownPreventionLock locker;
  40. if (isAlreadyShutDown()) {
  41. return;
  42. }
  43. shutdown(ShutdownCalledFrom::Object);
  44. }