1 /**
2 * \brief Use and generate random data into a file via the CTR_DBRG based on AES
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_CTR_DRBG_C) && defined(MBEDTLS_ENTROPY_C) && \
13 defined(MBEDTLS_FS_IO)
14 #include "mbedtls/entropy.h"
15 #include "mbedtls/ctr_drbg.h"
16
17 #include <stdio.h>
18 #endif
19
20 #if !defined(MBEDTLS_CTR_DRBG_C) || !defined(MBEDTLS_ENTROPY_C) || \
21 !defined(MBEDTLS_FS_IO)
main(void)22 int main(void)
23 {
24 mbedtls_printf("MBEDTLS_CTR_DRBG_C and/or MBEDTLS_ENTROPY_C and/or MBEDTLS_FS_IO not defined.\n");
25 mbedtls_exit(0);
26 }
27 #else
28
29
main(int argc,char * argv[])30 int main(int argc, char *argv[])
31 {
32 FILE *f;
33 int i, k, ret = 1;
34 int exit_code = MBEDTLS_EXIT_FAILURE;
35 mbedtls_ctr_drbg_context ctr_drbg;
36 mbedtls_entropy_context entropy;
37 unsigned char buf[1024];
38
39 mbedtls_ctr_drbg_init(&ctr_drbg);
40
41 if (argc < 2) {
42 mbedtls_fprintf(stderr, "usage: %s <output filename>\n", argv[0]);
43 mbedtls_exit(exit_code);
44 }
45
46 if ((f = fopen(argv[1], "wb+")) == NULL) {
47 mbedtls_printf("failed to open '%s' for writing.\n", argv[1]);
48 mbedtls_exit(exit_code);
49 }
50
51 mbedtls_entropy_init(&entropy);
52 ret = mbedtls_ctr_drbg_seed(&ctr_drbg,
53 mbedtls_entropy_func,
54 &entropy,
55 (const unsigned char *) "RANDOM_GEN",
56 10);
57 if (ret != 0) {
58 mbedtls_printf("failed in mbedtls_ctr_drbg_seed: %d\n", ret);
59 goto cleanup;
60 }
61 mbedtls_ctr_drbg_set_prediction_resistance(&ctr_drbg, MBEDTLS_CTR_DRBG_PR_OFF);
62
63 #if defined(MBEDTLS_FS_IO)
64 ret = mbedtls_ctr_drbg_update_seed_file(&ctr_drbg, "seedfile");
65
66 if (ret == MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR) {
67 mbedtls_printf("Failed to open seedfile. Generating one.\n");
68 ret = mbedtls_ctr_drbg_write_seed_file(&ctr_drbg, "seedfile");
69 if (ret != 0) {
70 mbedtls_printf("failed in mbedtls_ctr_drbg_write_seed_file: %d\n", ret);
71 goto cleanup;
72 }
73 } else if (ret != 0) {
74 mbedtls_printf("failed in mbedtls_ctr_drbg_update_seed_file: %d\n", ret);
75 goto cleanup;
76 }
77 #endif
78
79 for (i = 0, k = 768; i < k; i++) {
80 ret = mbedtls_ctr_drbg_random(&ctr_drbg, buf, sizeof(buf));
81 if (ret != 0) {
82 mbedtls_printf("failed!\n");
83 goto cleanup;
84 }
85
86 fwrite(buf, 1, sizeof(buf), f);
87
88 mbedtls_printf("Generating %ldkb of data in file '%s'... %04.1f" \
89 "%% done\r",
90 (long) (sizeof(buf) * k / 1024),
91 argv[1],
92 (100 * (float) (i + 1)) / k);
93 fflush(stdout);
94 }
95
96 exit_code = MBEDTLS_EXIT_SUCCESS;
97
98 cleanup:
99 mbedtls_printf("\n");
100
101 fclose(f);
102 mbedtls_ctr_drbg_free(&ctr_drbg);
103 mbedtls_entropy_free(&entropy);
104
105 mbedtls_exit(exit_code);
106 }
107 #endif /* MBEDTLS_CTR_DRBG_C && MBEDTLS_ENTROPY_C */
108