1 /**
2  *  \brief Generate random data into a file
3  *
4  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
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  *  This file is part of mbed TLS (https://tls.mbed.org)
20  */
21 
22 #if !defined(MBEDTLS_CONFIG_FILE)
23 #include "mbedtls/config.h"
24 #else
25 #include MBEDTLS_CONFIG_FILE
26 #endif
27 
28 #if defined(MBEDTLS_PLATFORM_C)
29 #include "mbedtls/platform.h"
30 #else
31 #include <stdio.h>
32 #define mbedtls_fprintf    fprintf
33 #define mbedtls_printf     printf
34 #endif
35 
36 #if defined(MBEDTLS_HAVEGE_C) && defined(MBEDTLS_FS_IO)
37 #include "mbedtls/havege.h"
38 
39 #include <stdio.h>
40 #include <time.h>
41 #endif
42 
43 #if !defined(MBEDTLS_HAVEGE_C) || !defined(MBEDTLS_FS_IO)
main(void)44 int main( void )
45 {
46     mbedtls_printf("MBEDTLS_HAVEGE_C not defined.\n");
47     return( 0 );
48 }
49 #else
main(int argc,char * argv[])50 int main( int argc, char *argv[] )
51 {
52     FILE *f;
53     time_t t;
54     int i, k, ret = 0;
55     mbedtls_havege_state hs;
56     unsigned char buf[1024];
57 
58     if( argc < 2 )
59     {
60         mbedtls_fprintf( stderr, "usage: %s <output filename>\n", argv[0] );
61         return( 1 );
62     }
63 
64     if( ( f = fopen( argv[1], "wb+" ) ) == NULL )
65     {
66         mbedtls_printf( "failed to open '%s' for writing.\n", argv[1] );
67         return( 1 );
68     }
69 
70     mbedtls_havege_init( &hs );
71 
72     t = time( NULL );
73 
74     for( i = 0, k = 768; i < k; i++ )
75     {
76         if( mbedtls_havege_random( &hs, buf, sizeof( buf ) ) != 0 )
77         {
78             mbedtls_printf( "Failed to get random from source.\n" );
79 
80             ret = 1;
81             goto exit;
82         }
83 
84         fwrite( buf, sizeof( buf ), 1, f );
85 
86         mbedtls_printf( "Generating %ldkb of data in file '%s'... %04.1f" \
87                 "%% done\r", (long)(sizeof(buf) * k / 1024), argv[1], (100 * (float) (i + 1)) / k );
88         fflush( stdout );
89     }
90 
91     if( t == time( NULL ) )
92         t--;
93 
94     mbedtls_printf(" \n ");
95 
96 exit:
97     mbedtls_havege_free( &hs );
98     fclose( f );
99     return( ret );
100 }
101 #endif /* MBEDTLS_HAVEGE_C */
102