gen_random_havege.c 2.4 KB

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