gen_entropy.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /**
  2. * \brief Use and generate multiple entropies calls 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_ENTROPY_C) && defined(MBEDTLS_FS_IO)
  34. #include "mbedtls/entropy.h"
  35. #include <stdio.h>
  36. #endif
  37. #if !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_FS_IO)
  38. int main( void )
  39. {
  40. mbedtls_printf("MBEDTLS_ENTROPY_C and/or MBEDTLS_FS_IO not defined.\n");
  41. return( 0 );
  42. }
  43. #else
  44. int main( int argc, char *argv[] )
  45. {
  46. FILE *f;
  47. int i, k, ret;
  48. mbedtls_entropy_context entropy;
  49. unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
  50. if( argc < 2 )
  51. {
  52. mbedtls_fprintf( stderr, "usage: %s <output filename>\n", argv[0] );
  53. return( 1 );
  54. }
  55. if( ( f = fopen( argv[1], "wb+" ) ) == NULL )
  56. {
  57. mbedtls_printf( "failed to open '%s' for writing.\n", argv[1] );
  58. return( 1 );
  59. }
  60. mbedtls_entropy_init( &entropy );
  61. for( i = 0, k = 768; i < k; i++ )
  62. {
  63. ret = mbedtls_entropy_func( &entropy, buf, sizeof( buf ) );
  64. if( ret != 0 )
  65. {
  66. mbedtls_printf("failed!\n");
  67. goto cleanup;
  68. }
  69. fwrite( buf, 1, sizeof( buf ), f );
  70. mbedtls_printf( "Generating %ldkb of data in file '%s'... %04.1f" \
  71. "%% done\r", (long)(sizeof(buf) * k / 1024), argv[1], (100 * (float) (i + 1)) / k );
  72. fflush( stdout );
  73. }
  74. ret = 0;
  75. cleanup:
  76. mbedtls_printf( "\n" );
  77. fclose( f );
  78. mbedtls_entropy_free( &entropy );
  79. return( ret );
  80. }
  81. #endif /* MBEDTLS_ENTROPY_C */