gen_entropy.c (1879B)
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 OR GPL-2.0-or-later 6 */ 7 8 #include "mbedtls/build_info.h" 9 10 #include "mbedtls/platform.h" 11 12 #if defined(MBEDTLS_ENTROPY_C) && defined(MBEDTLS_FS_IO) 13 #include "mbedtls/entropy.h" 14 15 #include <stdio.h> 16 #endif 17 18 #if !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_FS_IO) 19 int main(void) 20 { 21 mbedtls_printf("MBEDTLS_ENTROPY_C and/or MBEDTLS_FS_IO not defined.\n"); 22 mbedtls_exit(0); 23 } 24 #else 25 26 27 int main(int argc, char *argv[]) 28 { 29 FILE *f; 30 int i, k, ret = 1; 31 int exit_code = MBEDTLS_EXIT_FAILURE; 32 mbedtls_entropy_context entropy; 33 unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE]; 34 35 if (argc < 2) { 36 mbedtls_fprintf(stderr, "usage: %s <output filename>\n", argv[0]); 37 mbedtls_exit(exit_code); 38 } 39 40 if ((f = fopen(argv[1], "wb+")) == NULL) { 41 mbedtls_printf("failed to open '%s' for writing.\n", argv[1]); 42 mbedtls_exit(exit_code); 43 } 44 45 mbedtls_entropy_init(&entropy); 46 47 for (i = 0, k = 768; i < k; i++) { 48 ret = mbedtls_entropy_func(&entropy, buf, sizeof(buf)); 49 if (ret != 0) { 50 mbedtls_printf(" failed\n ! mbedtls_entropy_func returned -%04X\n", 51 (unsigned int) ret); 52 goto cleanup; 53 } 54 55 fwrite(buf, 1, sizeof(buf), f); 56 57 mbedtls_printf("Generating %ldkb of data in file '%s'... %04.1f" \ 58 "%% done\r", 59 (long) (sizeof(buf) * k / 1024), 60 argv[1], 61 (100 * (float) (i + 1)) / k); 62 fflush(stdout); 63 } 64 65 exit_code = MBEDTLS_EXIT_SUCCESS; 66 67 cleanup: 68 mbedtls_printf("\n"); 69 70 fclose(f); 71 mbedtls_entropy_free(&entropy); 72 73 mbedtls_exit(exit_code); 74 } 75 #endif /* MBEDTLS_ENTROPY_C */