zip_random_win32.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. zip_random_win32.c -- fill the user's buffer with random stuff (Windows version)
  3. Copyright (C) 2016-2021 Dieter Baron and Thomas Klausner
  4. This file is part of libzip, a library to manipulate ZIP archives.
  5. The authors can be contacted at <libzip@nih.at>
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions
  8. are met:
  9. 1. Redistributions of source code must retain the above copyright
  10. notice, this list of conditions and the following disclaimer.
  11. 2. Redistributions in binary form must reproduce the above copyright
  12. notice, this list of conditions and the following disclaimer in
  13. the documentation and/or other materials provided with the
  14. distribution.
  15. 3. The names of the authors may not be used to endorse or promote
  16. products derived from this software without specific prior
  17. written permission.
  18. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
  19. OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  21. ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
  22. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  23. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  24. GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  25. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  26. IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  27. OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  28. IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. #include "zipint.h"
  31. #ifdef HAVE_CRYPTO
  32. #include "zip_crypto.h"
  33. #endif
  34. #include <windows.h>
  35. #ifndef HAVE_SECURE_RANDOM
  36. #include <wincrypt.h>
  37. ZIP_EXTERN bool
  38. zip_secure_random(zip_uint8_t *buffer, zip_uint16_t length) {
  39. HCRYPTPROV hprov;
  40. if (!CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
  41. return false;
  42. }
  43. if (!CryptGenRandom(hprov, length, buffer)) {
  44. return false;
  45. }
  46. if (!CryptReleaseContext(hprov, 0)) {
  47. return false;
  48. }
  49. return true;
  50. }
  51. #endif
  52. #ifndef HAVE_RANDOM_UINT32
  53. #include <stdlib.h>
  54. zip_uint32_t
  55. zip_random_uint32(void) {
  56. static bool seeded = false;
  57. zip_uint32_t value;
  58. if (zip_secure_random((zip_uint8_t *)&value, sizeof(value))) {
  59. return value;
  60. }
  61. if (!seeded) {
  62. srand((unsigned int)time(NULL));
  63. }
  64. return (zip_uint32_t)rand();
  65. }
  66. #endif