rand_util_win.cc 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/rand_util.h"
  5. #include <windows.h>
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. // #define needed to link in RtlGenRandom(), a.k.a. SystemFunction036. See the
  9. // "Community Additions" comment on MSDN here:
  10. // http://msdn.microsoft.com/en-us/library/windows/desktop/aa387694.aspx
  11. #define SystemFunction036 NTAPI SystemFunction036
  12. #include <NTSecAPI.h>
  13. #undef SystemFunction036
  14. #include <algorithm>
  15. #include <limits>
  16. #include "base/check.h"
  17. namespace base {
  18. void RandBytes(void* output, size_t output_length) {
  19. char* output_ptr = static_cast<char*>(output);
  20. while (output_length > 0) {
  21. const ULONG output_bytes_this_pass = static_cast<ULONG>(std::min(
  22. output_length, static_cast<size_t>(std::numeric_limits<ULONG>::max())));
  23. const bool success =
  24. RtlGenRandom(output_ptr, output_bytes_this_pass) != FALSE;
  25. CHECK(success);
  26. output_length -= output_bytes_this_pass;
  27. output_ptr += output_bytes_this_pass;
  28. }
  29. }
  30. } // namespace base