gen_entropy.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * \brief Use and generate multiple entropies calls into a file
  3. *
  4. * Copyright The Mbed TLS Contributors
  5. * SPDX-License-Identifier: Apache-2.0
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  8. * not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  15. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. #include "mbedtls/build_info.h"
  20. #include "mbedtls/platform.h"
  21. #if defined(MBEDTLS_ENTROPY_C) && defined(MBEDTLS_FS_IO)
  22. #include "mbedtls/entropy.h"
  23. #include <stdio.h>
  24. #endif
  25. #if !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_FS_IO)
  26. int main(void)
  27. {
  28. mbedtls_printf("MBEDTLS_ENTROPY_C and/or MBEDTLS_FS_IO not defined.\n");
  29. mbedtls_exit(0);
  30. }
  31. #else
  32. int main(int argc, char *argv[])
  33. {
  34. FILE *f;
  35. int i, k, ret = 1;
  36. int exit_code = MBEDTLS_EXIT_FAILURE;
  37. mbedtls_entropy_context entropy;
  38. unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
  39. if (argc < 2) {
  40. mbedtls_fprintf(stderr, "usage: %s <output filename>\n", argv[0]);
  41. mbedtls_exit(exit_code);
  42. }
  43. if ((f = fopen(argv[1], "wb+")) == NULL) {
  44. mbedtls_printf("failed to open '%s' for writing.\n", argv[1]);
  45. mbedtls_exit(exit_code);
  46. }
  47. mbedtls_entropy_init(&entropy);
  48. for (i = 0, k = 768; i < k; i++) {
  49. ret = mbedtls_entropy_func(&entropy, buf, sizeof(buf));
  50. if (ret != 0) {
  51. mbedtls_printf(" failed\n ! mbedtls_entropy_func returned -%04X\n",
  52. (unsigned int) ret);
  53. goto cleanup;
  54. }
  55. fwrite(buf, 1, sizeof(buf), f);
  56. mbedtls_printf("Generating %ldkb of data in file '%s'... %04.1f" \
  57. "%% done\r",
  58. (long) (sizeof(buf) * k / 1024),
  59. argv[1],
  60. (100 * (float) (i + 1)) / k);
  61. fflush(stdout);
  62. }
  63. exit_code = MBEDTLS_EXIT_SUCCESS;
  64. cleanup:
  65. mbedtls_printf("\n");
  66. fclose(f);
  67. mbedtls_entropy_free(&entropy);
  68. mbedtls_exit(exit_code);
  69. }
  70. #endif /* MBEDTLS_ENTROPY_C */